Skip to content

Agent Mesh

sam-one: announce the tunnel URL only once DNS has it; docs: a mesh in 30 seconds

Antonio Ojea57ec4e38cd3c
diff --git a/cmd/sam-one/admin.go b/cmd/sam-one/admin.go
index b1f13ed5..87714b05 100644
--- a/cmd/sam-one/admin.go
+++ b/cmd/sam-one/admin.go
@@ -20,6 +20,7 @@ import (
"fmt"
"io"
"net/http"
+ "os"
"strings"
"text/tabwriter"
"time"
@@ -182,6 +183,10 @@ func newAdminSubcommands() []*cobra.Command {
)
addSharedFlags := func(cmd *cobra.Command) {
+ // cobra's cmd.Print* goes to stderr unless told otherwise; results
+ // belong on stdout so `token create | awk` and $(...) capture them.
+ cmd.SetOut(os.Stdout)
+ cmd.SetErr(os.Stderr)
cmd.PersistentFlags().StringVar(&server, "server", "http://127.0.0.1:8080", "Base URL of the running sam-one server")
cmd.PersistentFlags().StringVar(&adminTokenPath, "admin-token-path", "", "File containing the admin API bearer token (or env SAM_ADMIN_TOKEN, or read from --data-dir)")
cmd.PersistentFlags().StringVar(&dataDir, "data-dir", ".", "sam-one data directory holding the persisted admin token")
@@ -209,7 +214,7 @@ func newAdminSubcommands() []*cobra.Command {
cmd.Printf("Token: %s\n", created.Token)
cmd.Printf("Role: %s\n", created.Role)
cmd.Printf("Expires: %s\n", created.ExpiresAt)
- cmd.Println("The plain token is shown only once; store it now.")
+ cmd.PrintErrln("The plain token is shown only once; store it now.")
return nil
},
}
diff --git a/internal/tunnel/cloudflare.go b/internal/tunnel/cloudflare.go
index 0be0e418..21fa0b58 100644
--- a/internal/tunnel/cloudflare.go
+++ b/internal/tunnel/cloudflare.go
@@ -20,11 +20,14 @@ import (
"errors"
"fmt"
"io"
+ "net"
"net/http"
+ "net/url"
"os"
"os/exec"
"regexp"
"runtime"
+ "strings"
"sync"
"syscall"
"time"
@@ -49,7 +52,8 @@ 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 bounds how long Open waits for the URL and then for its
+ // hostname to be published in DNS; 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.
@@ -63,6 +67,10 @@ type Cloudflare struct {
ReleaseURL string
// HTTPClient performs the download; nil uses a 10 minute timeout.
HTTPClient *http.Client
+ // LookupHost asks whether the assigned hostname exists yet; nil asks
+ // the zone's authoritative nameserver (see authoritativeLookup). Tests
+ // stub it.
+ LookupHost func(ctx context.Context, host string) ([]string, error)
}
// quickTunnelURL matches the assigned hostname in cloudflared's banner. The
@@ -94,6 +102,7 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
if timeout <= 0 {
timeout = 30 * time.Second
}
+ deadline := time.Now().Add(timeout)
// The process outlives Open: its lifetime is the tunnel's, ended by Close.
procCtx, cancel := context.WithCancel(context.Background())
@@ -120,6 +129,7 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
select {
case u := <-urlCh:
t.url = u
+ c.awaitPublished(ctx, u, deadline)
return t, nil
case <-t.done:
return nil, fmt.Errorf("cloudflared exited before publishing a URL: %w", t.Err())
@@ -132,6 +142,76 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
}
}
+// awaitPublished blocks until the tunnel hostname exists in DNS, the deadline
+// passes or ctx ends. A quick-tunnel record appears a few seconds after
+// cloudflared prints the URL, and a device that asks before then is told the
+// host does not exist, so the URL must not be announced earlier. Missing the
+// deadline is not an error: the tunnel works once DNS catches up.
+func (c *Cloudflare) awaitPublished(ctx context.Context, rawURL string, deadline time.Time) {
+ u, err := url.Parse(rawURL)
+ if err != nil {
+ return
+ }
+ lookup := c.LookupHost
+ if lookup == nil {
+ lookup = authoritativeLookup
+ }
+ for {
+ lctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ _, err := lookup(lctx, u.Hostname())
+ cancel()
+ if err == nil {
+ return
+ }
+ if time.Now().After(deadline) {
+ logger.Warnf("%s is not published in DNS yet; devices may need a moment before they can reach it", u.Hostname())
+ return
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(500 * time.Millisecond):
+ }
+ }
+}
+
+// authoritativeLookup resolves host at its zone's own nameserver, bypassing
+// every cache in between. Asking a recursive resolver before the record
+// exists makes it cache the NXDOMAIN (the zone's SOA allows 30 minutes) and
+// strands every device behind that resolver, including a sam-node on this
+// very machine; the authoritative server has no cache to poison.
+func authoritativeLookup(ctx context.Context, host string) ([]string, error) {
+ zone := host[strings.IndexByte(host, '.')+1:]
+ nss, err := net.DefaultResolver.LookupNS(ctx, zone)
+ if err != nil {
+ return nil, err
+ }
+ if len(nss) == 0 {
+ return nil, fmt.Errorf("no nameservers for %s", zone)
+ }
+ addrs, err := net.DefaultResolver.LookupHost(ctx, nss[0].Host)
+ if err != nil {
+ return nil, err
+ }
+ if len(addrs) == 0 {
+ return nil, fmt.Errorf("no address for nameserver %s", nss[0].Host)
+ }
+ return lookupAt(ctx, net.JoinHostPort(addrs[0], "53"), host)
+}
+
+// lookupAt resolves host by asking only the nameserver at server.
+func lookupAt(ctx context.Context, server, host string) ([]string, error) {
+ r := &net.Resolver{
+ PreferGo: true,
+ Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, server)
+ },
+ }
+ // The trailing dot makes the name absolute so no search domain is tried.
+ return r.LookupHost(ctx, host+".")
+}
+
// 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 != "" {
diff --git a/internal/tunnel/cloudflare_test.go b/internal/tunnel/cloudflare_test.go
index fb9ba954..e61bcf07 100644
--- a/internal/tunnel/cloudflare_test.go
+++ b/internal/tunnel/cloudflare_test.go
@@ -22,6 +22,7 @@ import (
"crypto/sha256"
"encoding/hex"
"errors"
+ "net"
"net/http"
"net/http/httptest"
"os"
@@ -31,6 +32,8 @@ import (
"sync/atomic"
"testing"
"time"
+
+ "golang.org/x/net/dns/dnsmessage"
)
// stubCloudflared writes a shell script that mimics cloudflared's banner on
@@ -44,6 +47,61 @@ func stubCloudflared(t *testing.T, body string) string {
return path
}
+// resolved is a LookupHost for tests whose fake hostnames exist nowhere.
+func resolved(context.Context, string) ([]string, error) { return []string{"192.0.2.1"}, nil }
+
+// fakeAuthoritative starts a UDP nameserver that answers NXDOMAIN for the
+// first misses queries and an A record afterwards, like the zone's own
+// server watching a record get created. It returns its address and the
+// query counter.
+func fakeAuthoritative(t *testing.T, misses int32) (string, *atomic.Int32) {
+ t.Helper()
+ pc, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = pc.Close() })
+ var n atomic.Int32
+ go func() {
+ buf := make([]byte, 512)
+ for {
+ sz, from, err := pc.ReadFrom(buf)
+ if err != nil {
+ return
+ }
+ var q dnsmessage.Message
+ if err := q.Unpack(buf[:sz]); err != nil || len(q.Questions) != 1 {
+ continue
+ }
+ resp := dnsmessage.Message{
+ Header: dnsmessage.Header{ID: q.ID, Response: true, Authoritative: true, RCode: dnsmessage.RCodeNameError},
+ Questions: q.Questions,
+ }
+ // Go asks A and AAAA in parallel; only A queries advance the
+ // record's existence, AAAA just mirrors the current state.
+ exists := n.Load() > misses
+ if q.Questions[0].Type == dnsmessage.TypeA {
+ exists = n.Add(1) > misses
+ }
+ if exists {
+ resp.RCode = dnsmessage.RCodeSuccess
+ if q.Questions[0].Type == dnsmessage.TypeA {
+ resp.Answers = []dnsmessage.Resource{{
+ Header: dnsmessage.ResourceHeader{Name: q.Questions[0].Name, Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.AResource{A: [4]byte{192, 0, 2, 1}},
+ }}
+ }
+ }
+ out, err := resp.Pack()
+ if err != nil {
+ continue
+ }
+ _, _ = pc.WriteTo(out, from)
+ }
+ }()
+ return pc.LocalAddr().String(), &n
+}
+
func TestCloudflareOpenParsesQuickTunnelURL(t *testing.T) {
bin := stubCloudflared(t, `
[ "$1" = tunnel ] && [ "$2" = --url ] || { echo "bad args: $*" >&2; exit 2; }
@@ -57,7 +115,7 @@ echo "INF +------------------------------------------------------------+" >&2
trap 'exit 0' TERM
while :; do sleep 1; done
`)
- p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second}
+ p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second, LookupHost: resolved}
tun, err := p.Open(context.Background(), "http://127.0.0.1:18080")
if err != nil {
t.Fatalf("Open: %v", err)
@@ -106,6 +164,76 @@ func TestCloudflareOpenTimesOutWithoutURL(t *testing.T) {
}
}
+// Open must not hand back a URL nobody can resolve yet: the phone that scans
+// the QR code in the next second would be told the host does not exist.
+func TestCloudflareOpenWaitsForHostnameToBePublished(t *testing.T) {
+ bin := stubCloudflared(t, idleConnector)
+ var lookups atomic.Int32
+ p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second, LookupHost: func(_ context.Context, host string) ([]string, error) {
+ if host != "installed-quick-1234.trycloudflare.com" {
+ t.Errorf("lookup of %q, want the tunnel hostname", host)
+ }
+ if lookups.Add(1) <= 2 {
+ return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
+ }
+ return []string{"192.0.2.1"}, nil
+ }}
+ start := time.Now()
+ tun, err := p.Open(context.Background(), "http://127.0.0.1:1")
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ _ = tun.Close()
+ if n := lookups.Load(); n != 3 {
+ t.Fatalf("lookups = %d, want 3 (two NXDOMAIN, then an answer)", n)
+ }
+ if waited := time.Since(start); waited < time.Second {
+ t.Fatalf("Open returned after %s, before the name was published", waited)
+ }
+}
+
+// A name that never shows up delays Open by at most Timeout; the tunnel is
+// still returned because DNS, not the tunnel, is what is lagging.
+func TestCloudflareOpenGivesUpOnDNSAtDeadline(t *testing.T) {
+ bin := stubCloudflared(t, idleConnector)
+ p := &Cloudflare{Binary: bin, Timeout: time.Second, LookupHost: func(_ context.Context, host string) ([]string, error) {
+ return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
+ }}
+ start := time.Now()
+ tun, err := p.Open(context.Background(), "http://127.0.0.1:1")
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ _ = tun.Close()
+ if waited := time.Since(start); waited < time.Second || waited > 4*time.Second {
+ t.Fatalf("Open took %s, want about the 1s timeout", waited)
+ }
+ if tun.URL() != "https://installed-quick-1234.trycloudflare.com" {
+ t.Fatalf("URL = %q", tun.URL())
+ }
+}
+
+// lookupAt asks only the given server, so a recursive resolver in between
+// never sees (and never caches) a query for a name that does not exist yet.
+func TestLookupAtAsksOnlyTheGivenServer(t *testing.T) {
+ server, queries := fakeAuthoritative(t, 1)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ _, err := lookupAt(ctx, server, "fresh-quick-1234.trycloudflare.com")
+ var dnsErr *net.DNSError
+ if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound {
+ t.Fatalf("first lookup err = %v, want IsNotFound", err)
+ }
+ addrs, err := lookupAt(ctx, server, "fresh-quick-1234.trycloudflare.com")
+ if err != nil || len(addrs) != 1 || addrs[0] != "192.0.2.1" {
+ t.Fatalf("second lookup = %v, %v; want [192.0.2.1]", addrs, err)
+ }
+ if n := queries.Load(); n < 2 {
+ t.Fatalf("fake server saw %d queries, want the lookups to reach it", n)
+ }
+}
+
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) {
@@ -180,6 +308,7 @@ func TestCloudflareDownloadsPinnedReleaseWithConsent(t *testing.T) {
InstallDir: dir,
ReleaseURL: base,
Timeout: 5 * time.Second,
+ LookupHost: resolved,
Consent: func(version, url string) bool {
asked = append(asked, version+" "+url)
return true
@@ -238,7 +367,7 @@ 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 }}
+ p := &Cloudflare{InstallDir: dir, ReleaseURL: base, Timeout: 5 * time.Second, LookupHost: resolved, 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.
diff --git a/mobile/sam-node-app/README.md b/mobile/sam-node-app/README.md
index 8432bfa5..99d1354f 100644
--- a/mobile/sam-node-app/README.md
+++ b/mobile/sam-node-app/README.md
@@ -1,4 +1,4 @@
-# SAM Node Mobile (Flutter Client)
+# SAM Connect (Flutter Client)
This folder contains a Flutter application that packages and runs the native Go-based `sam-node` mesh client on mobile devices (Android and iOS) using Go's CGO compiler and Dart FFI (Foreign Function Interface).
@@ -97,7 +97,7 @@ Publishing is keyless: [`hack/publish-play.sh`](../../hack/publish-play.sh) driv
Once launched, the app (installed as **SAM Connect**, application id `dev.sammesh.connect`) asks you to enroll, then shows the dashboard:
-1. **Scan enrollment code**: The primary path. `sam-one` prints a single-use `sam://enroll?server=...&token=...` QR code at startup (and on demand with `sam-one token qr`); scan it, confirm the control plane hostname, and the app enrolls through `POST /enroll` with no identity provider involved. The phone's stock camera app can scan it too: the `sam://` link opens SAM Connect. Only `https://` control planes are accepted (plaintext `http://` for loopback only), because the control plane is the device's trust root. See [Device Enrollment](../../site/content/docs/user/device-enrollment.md).
+1. **Scan enrollment code**: The primary path. `sam-one` prints a single-use `sam://enroll?server=...&token=...` QR code at startup (and on demand with `sam-one token qr`); scan it, confirm the control plane hostname, and the app enrolls through `POST /enroll` with no identity provider involved. The phone's stock camera app can scan it too: the `sam://` link opens SAM Connect. Only `https://` control planes are accepted (plaintext `http://` for loopback only), because the control plane is the device's trust root. See [A Mesh in 30 Seconds](../../site/content/docs/user/device-enrollment.md).
2. **Enter details manually**: Paste a whole `sam://enroll` link or a bare bootstrap token together with the **Control plane URL**, then **Join with token**. On a full control plane, mint the token with `POST /admin/bootstrap-tokens` (see `development/kind/run-local-node.sh`); on `sam-one`, `sam-one token create`. Below it, **Login & Enroll (Browser)** and **Device Login** are the OIDC alternatives: the app reads the issuer from the control plane's `/info` endpoint and opens a login.
3. **Local API Token**: The bearer token that secures the local sidecar REST API. It is generated on first launch and kept in the app's private storage; view, copy or regenerate it on the **Config** tab. There is no default: Android loopback is shared by every installed app, so a fixed value would let any of them act as this node.
4. **Labels**: Set on the **Config** tab *before* enrolling; they are attested into the node's Biscuit at that point.
diff --git a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
index 5d328a8a..caac851c 100644
--- a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
+++ b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
@@ -67,7 +67,7 @@
<property
android:name="android.app.appfunctions.app_function_schema_version"
android:value="1" />
- <!-- Foreground Service for keeping SAM Node alive -->
+ <!-- Foreground Service that keeps the SAM Connect node alive -->
<service
android:name=".SamNodeForegroundService"
android:foregroundServiceType="connectedDevice|location"
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
index ab151147..f1293061 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
@@ -79,8 +79,8 @@ class SamNodeForegroundService : Service() {
private fun createNotification(): Notification {
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
- .setContentTitle("SAM Node Running")
- .setContentText("Maintaining mesh connection in background")
+ .setContentTitle("SAM Connect is running")
+ .setContentText("Maintaining the mesh connection in the background")
.setSmallIcon(android.R.drawable.ic_menu_share) // Placeholder icon
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW) // Low priority to avoid annoying user, but enough for Foreground
@@ -90,8 +90,8 @@ class SamNodeForegroundService : Service() {
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- val name = "SAM Node Service"
- val descriptionText = "Keeps SAM Node alive in background"
+ val name = "SAM Connect mesh connection"
+ val descriptionText = "Keeps SAM Connect connected to the mesh in the background"
val importance = NotificationManager.IMPORTANCE_LOW
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dart
index 4a7a7113..4e5870a8 100644
--- a/mobile/sam-node-app/lib/main.dart
+++ b/mobile/sam-node-app/lib/main.dart
@@ -8,7 +8,6 @@ import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
-import 'package:firebase_ai/firebase_ai.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
@@ -81,7 +80,7 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
- title: 'SAM Node Control',
+ title: 'SAM Connect',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true,
@@ -137,7 +136,8 @@ class _NodeControlPageState extends State<NodeControlPage> {
bool?
_isEnrolled; // null = checking, false = show enrollment, true = show dashboard
bool _running = false;
- String _status = 'Disconnected';
+ // Empty until something happens; the enrollment screen shows it as a card.
+ String _status = '';
String _nodeID = '';
int _connectedPeers = 0;
int _dhtSize = 0;
@@ -1185,7 +1185,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
- appBar: AppBar(title: const Text('SAM Node Mobile')),
+ appBar: AppBar(title: const Text('SAM Connect')),
body: _selectedTab == 0
? _buildBody()
: _selectedTab == 1
@@ -1669,31 +1669,8 @@ class _NodeControlPageState extends State<NodeControlPage> {
color: Colors.grey.shade100,
child: Padding(
padding: const EdgeInsets.all(16.0),
- child: Column(
- children: [
- Text('Status: $_status',
- style: const TextStyle(fontStyle: FontStyle.italic)),
- const SizedBox(height: 10),
- ElevatedButton(
- onPressed: () async {
- try {
- final model = FirebaseAI.googleAI().generativeModel(
- model: 'gemini-2.5-flash',
- );
- debugPrint('DEBUG: Model initialized: ${model.hashCode}');
- setState(() {
- _status = 'Debug: Model initialized';
- });
- } catch (e) {
- setState(() {
- _status = 'API Error: $e';
- });
- }
- },
- child: const Text('Debug API Connection'),
- ),
- ],
- ),
+ child: Text('Status: $_status',
+ style: const TextStyle(fontStyle: FontStyle.italic)),
),
),
],
diff --git a/site/content/docs/user/_index.md b/site/content/docs/user/_index.md
index 55528df0..f377a849 100644
--- a/site/content/docs/user/_index.md
+++ b/site/content/docs/user/_index.md
@@ -20,8 +20,8 @@ Welcome to the User & Operator Guides. This section provides detailed documentat
4. **[Production Kubernetes Deployment](kubernetes-deployment/)**
Deploy a production-grade mesh cluster in Kubernetes, including Dex OIDC setups, StatefulSet P2P routers, DNS A-record synchronizers, and Workload Identity ServiceAccount token projections.
-5. **[SAM Mobile App](mobile-app/)**
+5. **[SAM Connect](mobile-app/)**
Turn your mobile device into a SAM node, exposing sensors and telemetry securely to the mesh, and integrating with native OS assistants.
-6. **[Device Enrollment (QR Code)](device-enrollment/)**
- Enroll phones by scanning a single-use `sam://enroll` code printed by `sam-one`, including publishing a laptop on a public https URL through a tunnel.
+6. **[A Mesh in 30 Seconds](device-enrollment/)**
+ Run `sam-one` on a laptop, scan the QR code with SAM Connect, and call a sensor on the phone from the laptop through the mesh. Two devices behind NAT, no server, domain or identity provider to set up first.
diff --git a/site/content/docs/user/cloud-run-deployment.md b/site/content/docs/user/cloud-run-deployment.md
index cb7b20ee..0e625e00 100644
--- a/site/content/docs/user/cloud-run-deployment.md
+++ b/site/content/docs/user/cloud-run-deployment.md
@@ -204,4 +204,4 @@ the generated tokens; pass `--port 8080` (and optionally
`--bind-address`) for a fixed one, and `--external-url https://mesh.example.com`
when fronted by a reverse proxy or DNS name. On a laptop behind NAT,
`--tunnel cloudflare` publishes the port on a temporary public https URL
-instead; see [Device Enrollment](../device-enrollment/).
+instead; see [A Mesh in 30 Seconds](../device-enrollment/).
diff --git a/site/content/docs/user/device-enrollment.md b/site/content/docs/user/device-enrollment.md
index 3e994c9f..dff7b2a1 100644
--- a/site/content/docs/user/device-enrollment.md
+++ b/site/content/docs/user/device-enrollment.md
@@ -1,229 +1,216 @@
---
-title: "Device Enrollment (QR Code)"
-linkTitle: "Device Enrollment"
+title: "A Mesh in 30 Seconds"
+linkTitle: "A Mesh in 30 Seconds"
weight: 7
---
-# Enrolling Phones with a QR Code
+# A Mesh in 30 Seconds
-A phone joins the mesh the same way a `sam-node` does: it presents a
-bootstrap token to the control plane's `POST /enroll`, which spends the
-token and issues the device a Biscuit bound to its own key. The only thing
-a QR code adds is a way to hand the phone the two facts it needs without
-typing them:
+You have a laptop and a phone. Neither has a public IP address, they are
+not on the same network, and you want a program on the laptop to read a
+sensor on the phone, securely, without first setting up a server, a
+domain, a certificate or an identity provider.
+
+That is what `sam-one` is for: the whole SAM control plane, router and
+database in one binary on one port, and it prints a QR code the phone
+scans to join. Everything below was run exactly as written and timed from
+the moment `sam-one` started, on a fresh data directory:
```
-sam://enroll?server=<control-plane-url>&token=<bootstrap-token>
+ 10.3s sam-one: banner + QR printed
+ 13.7s phone: enrolled
+ 18.8s phone: node running, phone-sensors advertised
+ 19.6s laptop: enrolled
+ 24.9s laptop -> phone: {"battery_level": 64, "charging": true}
```
-The token is an ordinary bootstrap token, so the code grants exactly what
-the token grants — one enrollment, in the token's role, until it expires —
-against any SAM control plane, `sam-one` or a full `sam-control-plane`.
-
-## 1. Run `sam-one` on a public https URL
+The taps on the phone were scripted; with a human reading the dialog it
+lands around half a minute. The output is real, only the tokens are
+shortened.
-Phones only trust an **https** control plane (plaintext `http://` is
-accepted for loopback only): whoever answers that URL becomes the device's
-trust root, so `sam-one` refuses to draw a QR code for a plaintext address
-and tells you how to get one. Three ways, from a laptop to production:
+You need the `sam-one` and `sam-node` binaries on the laptop (`make` from
+a checkout, or a [release](https://github.com/google/sam/releases)) and
+**SAM Connect** on the phone, the Android app from the same release.
-**Laptop behind NAT — a tunnel.** `sam-one` can publish its single port on
-a temporary public hostname through a tunnel provider. The first one is
-[Cloudflare Quick Tunnels](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/),
-which need no account:
+## 1. Start the control plane
```bash
sam-one --data-dir ~/sam-one --tunnel cloudflare
```
-If `cloudflared` is not on your `PATH`, `sam-one` offers to download the
-pinned release from GitHub into `~/sam-one/bin`. The download is verified
-against a SHA-256 digest compiled into `sam-one`, re-verified before every
-launch, and only happens after you accept Cloudflare's license at the
-prompt (or pass `--tunnel-install` to accept up front, for scripts). Pass
-`--cloudflared-path` to use a copy you installed yourself.
+`--data-dir` holds the database, the router's identity and the generated
+tokens; delete it and you have a brand new mesh. `--tunnel cloudflare`
+publishes the single port on a temporary public `https` hostname through
+a [Cloudflare quick tunnel](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/),
+which needs no account. If `cloudflared` is not installed, `sam-one`
+offers to download the pinned release (checksum-verified, into
+`~/sam-one/bin`) once you accept Cloudflare's license at the prompt;
+`--tunnel-install` accepts it up front.
-Quick tunnels are for testing and demos: no uptime guarantee, a new
-hostname on every start, and no Server-Sent Events. Everything else works —
-enrollment, the web console, and the `wss` mesh transport nodes use to
-reach the embedded router.
+A few seconds later (`sam-one` waits until the new hostname is actually
+published in DNS before it prints anything, so what you see is live):
-**Cloud Run** terminates TLS for you; follow the
-[Cloud Run deployment guide](../cloud-run-deployment/) and set
-`SAM_EXTERNAL_URL` to the service URL.
+```
+══════════════════════════════════════════════════════════════════
+SAM standalone mesh is ready!
-**Your own VM and domain — a reverse proxy.** Put an ACME-capable proxy in
-front of the single port and tell `sam-one` its public name:
+API URL: https://fairy-museum-built-wing.trycloudflare.com
+Tunnel: https://fairy-museum-built-wing.trycloudflare.com -> http://0.0.0.0:33775
+Web Console: https://fairy-museum-built-wing.trycloudflare.com/console
+Router Peer: 12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY
+Admin Token: sam_adm_…
+Join Token: sam_tok_…
-```bash
-# Caddyfile: Let's Encrypt certificate, automatic renewal, WebSockets included.
-mesh.example.com {
- reverse_proxy 127.0.0.1:8080
-}
+To enroll a node:
+ sam-node join https://fairy-museum-built-wing.trycloudflare.com --bootstrap-token-path /home/you/sam-one/join-token
+══════════════════════════════════════════════════════════════════
-sam-one --data-dir /var/lib/sam-one --port 8080 --external-url https://mesh.example.com
+Scan with the SAM app to enroll a device into fairy-museum-built-wing.trycloudflare.com
+(single use, valid for 1h0m0s):
+
+█████████████████████████████████████████████
+████ ▄▄▄▄▄ ██▄ █ █ ▀ █▀▄▄▄▀ ▄▄▄ ▄▀▀ ▄▄▄▄▄ ████
+████ █ █ █ ████ ▀▀▄▄█▀▀▀▄▀█▀▄▄ ▀ █ █ ████
+████ █▄▄▄█ █ ▄███▀▀▀▀▀▄ ▄ ▄▄▄ █▄ ▄▀ █▄▄▄█ ████
+ …
+sam://enroll?server=https%3A%2F%2Ffairy-museum-built-wing.trycloudflare.com&token=sam_dev_…
+Token ID: 0b7acf609466 (revoke early with: sam-one token revoke 0b7acf609466)
```
-## 2. Read the code
+That is a running mesh. The web console is live at the URL shown, the
+join token lets `sam-node` processes in, and the QR code carries a fresh
+**single-use** token for one phone.
-With a public https URL, `sam-one` prints a device enrollment block under
-its startup banner whenever stdout is a terminal (`--enroll-qr=false` to
-suppress it, `--enroll-qr` to force it):
+## 2. Enroll the phone
-```
-Scan with the SAM app to enroll a device into brave-otter-quick-1234.trycloudflare.com
-(single use, valid for 1h0m0s):
+Open SAM Connect, tap **Scan enrollment code** and point it at the
+terminal. The app shows where the code leads before it spends the token;
+tap **Join**.
-█████████████████████████████████████
-████ ▄▄▄▄▄ █▀ █▀▀▄▀▄▀▀ █ ▄▄▄▄▄ ████
-...
+| Confirm the mesh | Running |
+|:---:|:---:|
+| ![Join this mesh?](/images/sam-connect-join.png) | ![Node is Running](/images/sam-connect-running.png) |
-sam://enroll?server=https%3A%2F%2Fbrave-otter-quick-1234.trycloudflare.com&token=sam_dev_...
-```
+On the **Services** tab switch **Battery Status** on, go back to the
+dashboard and tap **Start**. The phone is now a node: it generated its own
+key, was issued a credential bound to that key, connected to the router
+through the tunnel and advertised a `phone-sensors` service to the mesh.
+Note the **Node ID** on the dashboard; you will use it in a moment.
-Each code carries a fresh node token, minted for that boot and valid for
-one hour. By default it is **single use**: once a device has spent it,
-`POST /enroll` refuses it for anyone else. It is never persisted, so a
-stale screenshot is worthless.
+Scanning with the phone's stock camera app works too: the `sam://` link
+opens SAM Connect with the same dialog. Without a camera, **Enter details
+manually** takes the printed `sam://enroll…` line pasted as text.
-For more devices, or on a non-interactive deployment, mint a code on demand
-with the admin CLI:
+## 3. Join the laptop and call the phone
```bash
-# Admin credential: env, or --admin-token-path <file>; never a flag value.
-export SAM_ADMIN_TOKEN=... # from the banner, or <data-dir>/admin-token
-sam-one token qr --server https://brave-otter-quick-1234.trycloudflare.com
+sam-node run --control-plane https://fairy-museum-built-wing.trycloudflare.com \
+ --bootstrap-token-path ~/sam-one/join-token \
+ --data-dir ~/laptop-node --bind-addr=
```
-`--server` is both where the CLI talks to and the URL embedded in the code;
-pass `--enroll-url https://...` when devices reach the mesh on a different
-address than the admin does. `sam-one token list` shows every minted token
-with its usage count and status, and the standard `--role`/`--ttl-hours`
-tokens from `sam-one token create` work in the app's manual entry too.
+The node enrolls with the join token the banner pointed at. An empty
+`--bind-addr=` keeps its local API on a Unix socket only,
+`~/laptop-node/sam.sock`, so nothing on the laptop needs a token to use
+it. Now ask the phone for its battery, through the mesh:
-### One code for a whole room
+```bash
+PHONE=12D3KooWSCnbUoZ8Jv3EKGv17LqEWtnTMfZ3XYJUg2WTm5Gz2hUK # Node ID from the phone's dashboard
-A demo with an audience does not want one code per phone. Give the code a
-usage budget instead, and every device that scans it joins until the
-budget, the TTL or you say otherwise:
+curl -s --unix-socket ~/laptop-node/sam.sock \
+ -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_battery_status","arguments":{}}}' \
+ http://localhost/sam/$PHONE/mcp/phone-sensors/
+```
-```bash
-# Startup code good for 200 devices (projector-friendly).
-sam-one --data-dir ~/sam-one --tunnel cloudflare --enroll-qr-max-usages 200
+```json
+{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"battery_level\": 46, \"charging\": true}"}]}}
+```
+
+That request left the laptop's socket, crossed the tunnel to the router
+inside `sam-one`, was relayed to the phone over a connection the phone had
+opened outbound, and came back the same way. Both devices are behind NAT;
+neither accepted an inbound connection. Every hop was authenticated with
+the credentials minted at enrollment, and the phone's node checked the
+mesh policy before letting the call through.
-# Or mint one for the afternoon on a running mesh.
-sam-one token qr --server "$URL" --max-usages 200 --ttl-hours 4
+Any MCP client can do the same: the path is
+`/sam/<node-id>/mcp/<service>/` over that socket, and `tools/list` on it
+shows what the phone offers (`get_battery_status`, and `get_location` once
+you enable Location).
+
+## 4. Add more devices
+
+A second phone is another QR code. `sam-one token qr` mints one on a
+running mesh, and `--max-usages 50` makes a single code, projected on a
+screen, admit a whole room:
+
+```bash
+sam-one token qr --server https://fairy-museum-built-wing.trycloudflare.com --data-dir ~/sam-one
```
-The caption under the code says how many devices it admits and prints the
-token id. Anyone who photographs a shared code can enroll until it is
-exhausted, so end it when the session ends:
+A second laptop gets a scoped, single-use token instead of the standing
+join token:
```bash
-sam-one token list --server "$URL" # STATUS: active / exhausted / expired / revoked
-sam-one token revoke 9c75ab4a3122 --server "$URL"
+# On the sam-one host: mint the token straight into a file.
+sam-one token create --server https://fairy-museum-built-wing.trycloudflare.com \
+ --data-dir ~/sam-one --description "second laptop" \
+ | awk '/^Token:/{print $2}' > enroll-token
+
+# On the second laptop, with that file copied over:
+sam-node run --control-plane https://fairy-museum-built-wing.trycloudflare.com \
+ --bootstrap-token-path enroll-token --data-dir ~/node --bind-addr=
```
-Revoking a token stops further enrollments only; the devices it already
-admitted keep their identity. Remove one of those with
-`sam-one admin ban <peer-id>`, or, for a throwaway demo mesh, simply stop
-`sam-one` (a fresh data dir is a fresh mesh).
-
-On a full `sam-control-plane`, mint the token with
-`POST /admin/bootstrap-tokens` (`max_usages: 1`) and build the same
-`sam://enroll?...` string; the app does not care which binary is behind the
-URL.
-
-## 3. Enroll the phone
-
-In **SAM Connect** (the Android app):
-
-1. Tap **Scan enrollment code** and point the camera at the terminal. The
- app only accepts `sam://enroll` codes; any other QR is ignored with a
- hint.
-2. Confirm the control plane hostname in the dialog and tap **Join**. Labels
- set on the **Config** tab are attested into the device's Biscuit at this
- point.
-3. Start the node from the dashboard.
-
-Scanning with the phone's stock camera app works as well: the `sam://`
-link opens SAM Connect with the same confirmation dialog. **Enter details
-manually** covers everything else: paste the whole `sam://enroll` link or a
-bare token (with the control plane URL), or use the browser and device
-OIDC logins where the control plane is configured with an identity
-provider.
-
-A device that joined with a token has no login session to refresh, so its
-labels cannot be re-attested in place: **Re-enroll** is disabled for it,
-and changing labels means unenrolling and scanning a new code.
-
-## What the token does and does not do
-
-* One usage, one device. `POST /enroll` consumes a usage atomically before
- anything is minted, so devices racing on the last usage of a code cannot
- both win. The loser sees "Bootstrap token expired, revoked or exhausted".
-* The device keeps its identity, not the token. Its Biscuit is bound to the
- key it generated locally and is refreshed through `/refresh`; revoking it
- later is `sam-one admin ban <peer-id>`, exactly as for any node.
-* The token is scoped to the `sam:role:node` role. It cannot mint other
- tokens, approve enrollments or reach the admin API; the admin token never
- leaves the operator's terminal.
-* The code binds server and token together but the control plane does not
- pin a token to a hostname: a token is valid at whatever URL the same
- control plane answers on. Treat the printed line like the join token —
- it is a credential until it is spent or expires.
-
-## From demo to fleet
-
-`sam-one` is the same control plane, router and store as the split
-deployment in one process, so a device enrolled through a QR code gets the
-production credential lifecycle: a Biscuit bound to its own key, renewed
-through `POST /refresh` with a signed challenge well before its 24 h
-expiry, verified against rotating signing keys, revocable with
-`sam-one admin ban`. The mobile app runs the same renewal loop as
-`sam-node`. What separates a demo from a fleet is configuration:
-
-* **Drop the standing join token.** The auto-generated join token is a
- ten-year, unlimited-use secret meant for `sam-node join` on a laptop.
- Run with `--no-join-token`; devices then enroll only with tokens you
- mint (`token qr`, `token create`) or through OIDC.
-* **Seed a real policy.** Without `--policy-file` the first boot installs
- an open development policy (any enrolled node may declare any label and
- register any service) and says so in the log. Use
- `--control-plane-manual-enrollment` if each device should be approved in
- the console before it gets a credential.
-* **Pass secrets, don't read them off the screen.** Secrets are only ever
- read from a file (`--admin-token-path`, `--token-path`) or the environment
- (`SAM_ADMIN_TOKEN`, `SAM_TOKEN`); there is deliberately no flag that takes
- the value, so it never lands in `ps` output or shell history. When you
- supply them, the banner names the source instead of echoing the value into
- your logs. `--enroll-qr=false` keeps startup codes out of non-interactive
- logs.
-* **Give the mesh a stable https name.** A quick tunnel changes hostname on
- every start, and enrolled devices remember the URL they enrolled at —
- fine for an afternoon, fatal for a fleet. Use Cloud Run, a named tunnel
- on your own domain, or a reverse proxy with `--external-url`.
-* **Decide what happens to devices that go dark.** The signing key rotates
- every 24 h and stays valid for verification for a 1 h grace period. A
- device that renews inside that window is fine indefinitely; one that
- comes back later holds a Biscuit no current key can verify, and
- `/refresh` refuses it — the node exits rather than run unverified. Two
- knobs, and they are a trade-off:
- * Mint its token with `--autonomous-recovery`. The device may then
- recover on proof of possession of its key alone, whenever it returns.
- The cost is that a lost device keeps renewing until you ban it.
- * Or widen the window for everyone with
- `--control-plane-key-grace-period` (e.g. `168h` for a weekly check-in
- cadence). The cost is that a stolen credential also lives that long.
- Toggle recovery per device later from the console
- (`POST /admin/nodes/{peer-id}/autonomous-recovery`).
-* **Keep the data directory.** `router.key` is the mesh's identity;
- `sam.db` holds enrollments, tokens and policy. Back it up, or point
- `--db-driver postgres` at a managed database. `sam-one` is a singleton by
- design; when you need more than one control plane, move to the split
- components with the Helm chart.
-
-Want OIDC instead of tokens? Give `sam-one` an issuer (`--issuer`,
-`--allowed-audiences`, `--oidc-client-id`) and the app's **Login & Enroll**
-and **Device Login** flows work unchanged, as does signing in to the
-console as an OIDC admin.
+The same `curl` from that laptop returns the same battery reading.
+`sam-one token list` shows every token with its usage and status, and
+`sam-one token revoke <id>` ends one early. A device that is already
+enrolled stays enrolled until you say otherwise:
+`sam-one admin ban <node-id>` removes it.
+
+(`--data-dir` tells the CLI where to read the admin token; on another
+machine, export `SAM_ADMIN_TOKEN` or pass `--admin-token-path` instead. It
+is never a flag value.)
+
+## Why this is not a toy
+
+* **The phone's identity is a key it generated.** The token in the QR code
+ is spent once at `POST /enroll` and worthless afterwards; what the phone
+ keeps is a short-lived credential bound to its own key, renewed
+ automatically and revocable by node ID. The app runs the same renewal
+ loop as `sam-node`.
+* **The URL must be `https`.** The control plane is each device's trust
+ root, so SAM Connect refuses plaintext to anything but `localhost`, and
+ `sam-one` will not print a QR code for a plaintext address. The tunnel
+ is the zero-setup way to get `https` on a laptop; Cloud Run and a
+ reverse proxy with `--external-url` are the others (see the [Cloud Run
+ guide](../cloud-run-deployment/)).
+* **Nothing is routed by IP.** Services are found by name and called by
+ node ID; policy is evaluated on the service name, deny by default.
+* **`sam-one` is the real thing.** It runs the same control plane, router
+ and store as a Kubernetes deployment, in one process. What works here
+ works there.
+
+## Before you take it beyond a demo
+
+A quick tunnel changes hostname every start and comes with no uptime
+promise, and the first boot seeds an *open* development policy (the log
+says so). For anything with more than a handful of devices:
+
+* Give the mesh a stable `https` name and keep `~/sam-one`, or point
+ `--db-driver postgres` at a database.
+* Seed a real policy with `--policy-file`, and run with `--no-join-token`
+ so devices enroll only with tokens you mint.
+* Read the admin token from `SAM_ADMIN_TOKEN` or `--admin-token-path`
+ rather than the banner; `--enroll-qr=false` keeps codes out of
+ non-interactive logs.
+* Decide what happens to devices that go dark for more than a day: widen
+ `--control-plane-key-grace-period`, or mint their tokens with
+ `--autonomous-recovery`. The trade-off is how long a lost device can
+ keep renewing.
+* Want OIDC instead of tokens? Give `sam-one` an issuer (`--issuer`,
+ `--allowed-audiences`, `--oidc-client-id`) and the app's **Login &
+ Enroll** and **Device Login** flows work unchanged.
+
+Those are flags, not a different product.
diff --git a/site/content/docs/user/mobile-app.md b/site/content/docs/user/mobile-app.md
index 9ef8ec7f..09d633d1 100644
--- a/site/content/docs/user/mobile-app.md
+++ b/site/content/docs/user/mobile-app.md
@@ -1,12 +1,12 @@
---
-title: "SAM Mobile App (Android/iOS)"
-linkTitle: "Mobile App"
+title: "SAM Connect (Android/iOS)"
+linkTitle: "SAM Connect"
weight: 5
---
-# SAM Node Mobile (Flutter Client)
+# SAM Connect (Flutter Client)
-The SAM Mobile App is a Flutter application that packages and runs the native Go-based `sam-node` mesh client on mobile devices using Go's CGO compiler and Dart FFI (Foreign Function Interface).
+SAM Connect is a Flutter application that packages and runs the native Go-based `sam-node` mesh client on mobile devices using Go's CGO compiler and Dart FFI (Foreign Function Interface).
It allows you to turn your phone into a fully functional node in the Sovereign Agent Mesh, exposing device sensors and capabilities securely to AI agents.
@@ -37,7 +37,7 @@ Exposes capabilities directly to the OS registry, allowing native assistants (li
## How to Use the Application
-1. **Enrollment**: Tap **Scan enrollment code** and scan the `sam://enroll` QR code printed by `sam-one` (see [Device Enrollment](../device-enrollment/)), or open **Enter details manually** to paste a bootstrap token, or sign in through the control plane's identity provider (browser or device login) with its **Control plane URL** (e.g., `https://bananas.sam-mesh.dev`).
+1. **Enrollment**: Tap **Scan enrollment code** and scan the `sam://enroll` QR code printed by `sam-one` (see [A Mesh in 30 Seconds](../device-enrollment/)), or open **Enter details manually** to paste a bootstrap token, or sign in through the control plane's identity provider (browser or device login) with its **Control plane URL** (e.g., `https://bananas.sam-mesh.dev`).
2. **API Token**: A local API token securing local access is generated on first launch; view or regenerate it on the Config tab.
3. **Start Node**: Launches the background Go node runtime.
4. **Dashboard**: Monitor connected peers and DHT size.
diff --git a/site/static/images/sam-connect-join.png b/site/static/images/sam-connect-join.png
new file mode 100644
index 00000000..e07234c9
Binary files /dev/null and b/site/static/images/sam-connect-join.png differ
diff --git a/site/static/images/sam-connect-running.png b/site/static/images/sam-connect-running.png
new file mode 100644
index 00000000..e7d0c3e1
Binary files /dev/null and b/site/static/images/sam-connect-running.png differ
diff --git a/site/static/images/sam-connect-welcome.png b/site/static/images/sam-connect-welcome.png
new file mode 100644
index 00000000..80cf3005
Binary files /dev/null and b/site/static/images/sam-connect-welcome.png differ