Skip to content

Agent Mesh

mobile: SAM Connect scans sam://enroll codes and joins with a token

Antonio Ojea2f187e953134
diff --git a/mobile/sam-node-app/android/app/build.gradle.kts b/mobile/sam-node-app/android/app/build.gradle.kts
index abd9eeb9..95657c7e 100644
--- a/mobile/sam-node-app/android/app/build.gradle.kts
+++ b/mobile/sam-node-app/android/app/build.gradle.kts
@@ -7,7 +7,7 @@ plugins {
}
android {
- namespace = "com.example.sam_agent"
+ namespace = "dev.sammesh.connect"
compileSdk = 37 // Keep as 37, Gradle usually maps this correctly, but let's check if it needs to be 37
ndkVersion = flutter.ndkVersion
@@ -17,8 +17,7 @@ android {
}
defaultConfig {
- // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
- applicationId = "com.example.sam_agent"
+ applicationId = "dev.sammesh.connect"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
diff --git a/mobile/sam-node-app/android/app/google-services.json.tmpl b/mobile/sam-node-app/android/app/google-services.json.tmpl
index 08425908..a2213b11 100644
--- a/mobile/sam-node-app/android/app/google-services.json.tmpl
+++ b/mobile/sam-node-app/android/app/google-services.json.tmpl
@@ -9,7 +9,7 @@
"client_info": {
"mobilesdk_app_id": "1:123456789:android:123456789",
"android_client_info": {
- "package_name": "com.example.sam_agent"
+ "package_name": "dev.sammesh.connect"
}
},
"oauth_client": [],
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 1488396d..d3caae75 100644
--- a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
+++ b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
@@ -9,8 +9,10 @@
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
+ <!-- Scanning the sam://enroll QR code shown by the control plane. -->
+ <uses-permission android:name="android.permission.CAMERA"/>
<application
- android:label="sam_agent"
+ android:label="SAM Connect"
android:name=".SamApplication"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false">
@@ -39,6 +41,14 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
+ <!-- sam://enroll?server=...&token=... links: a stock camera app
+ scanning the enrollment QR hands the payload to this app. -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW"/>
+ <category android:name="android.intent.category.DEFAULT"/>
+ <category android:name="android.intent.category.BROWSABLE"/>
+ <data android:scheme="sam" android:host="enroll"/>
+ </intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/MainActivity.kt
similarity index 78%
rename from mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
rename to mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/MainActivity.kt
index eab8f192..bf29b0a7 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/MainActivity.kt
@@ -1,16 +1,35 @@
-package com.example.sam_agent
+package dev.sammesh.connect
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
+import android.content.Intent
import android.util.Log
import android.content.Context
class MainActivity : FlutterActivity() {
- private val CHANNEL = "com.example.sam_agent/mesh_expose"
+ private val CHANNEL = "dev.sammesh.connect/mesh_expose"
+ private val ENROLL_LINK_CHANNEL = "dev.sammesh.connect/enroll_link"
+ private var enrollLinkChannel: MethodChannel? = null
+
+ // A sam://enroll link that arrived before Dart asked for it (cold start).
+ private var pendingEnrollLink: String? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
+
+ pendingEnrollLink = enrollLinkOf(intent)
+ enrollLinkChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, ENROLL_LINK_CHANNEL).also { channel ->
+ channel.setMethodCallHandler { call, result ->
+ when (call.method) {
+ "getInitialLink" -> {
+ result.success(pendingEnrollLink)
+ pendingEnrollLink = null
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
@@ -102,4 +121,23 @@ class MainActivity : FlutterActivity() {
// Two decimal places of a degree is roughly 1.1 km at the equator.
private fun coarsen(degrees: Double): Double = Math.round(degrees * 100.0) / 100.0
+
+ // singleTop: a link opened while the app is running lands here instead of
+ // in a new activity, so it is pushed to Dart rather than queued.
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ val link = enrollLinkOf(intent) ?: return
+ val channel = enrollLinkChannel
+ if (channel != null) {
+ channel.invokeMethod("onLink", link)
+ } else {
+ pendingEnrollLink = link
+ }
+ }
+
+ private fun enrollLinkOf(intent: Intent?): String? {
+ val data = intent?.data ?: return null
+ if (intent.action != Intent.ACTION_VIEW || data.scheme != "sam") return null
+ return data.toString()
+ }
}
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamApplication.kt
similarity index 94%
rename from mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
rename to mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamApplication.kt
index 4642ca3d..18740de5 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamApplication.kt
@@ -1,4 +1,4 @@
-package com.example.sam_agent
+package dev.sammesh.connect
import android.app.Application
import androidx.appfunctions.service.AppFunctionConfiguration
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamFunctions.kt
similarity index 98%
rename from mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt
rename to mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamFunctions.kt
index 94c5339a..c6ab55f5 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamFunctions.kt
@@ -1,4 +1,4 @@
-package com.example.sam_agent
+package dev.sammesh.connect
import androidx.appfunctions.service.AppFunction
import androidx.appfunctions.AppFunctionContext
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
similarity index 99%
rename from mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
rename to mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
index 9e6fac94..ab151147 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/dev/sammesh/connect/SamNodeForegroundService.kt
@@ -1,4 +1,4 @@
-package com.example.sam_agent
+package dev.sammesh.connect
import android.app.Notification
import android.app.NotificationChannel
diff --git a/mobile/sam-node-app/lib/enroll_link.dart b/mobile/sam-node-app/lib/enroll_link.dart
new file mode 100644
index 00000000..b5251eae
--- /dev/null
+++ b/mobile/sam-node-app/lib/enroll_link.dart
@@ -0,0 +1,73 @@
+/// Device enrollment links.
+///
+/// A control plane (sam-one's terminal QR code, or any operator holding a
+/// bootstrap token) hands a device everything it needs in one string:
+///
+/// sam://enroll?server=<control-plane-url>&token=<bootstrap-token>
+///
+/// This mirrors `api.EnrollURI` / `api.ParseEnrollURI` in the Go tree and
+/// must stay in lockstep with it: same scheme, same host, same two query
+/// parameters, same transport rule for the server URL. The token is an
+/// ordinary bootstrap token, so the link grants exactly one enrollment in
+/// the token's role until it expires.
+///
+/// The control plane is the device's trust root, so the server must be
+/// https; plaintext http is accepted only to a loopback host (an emulator
+/// reaching the workstation over `adb reverse`). The Go node client inside
+/// the FFI enforces the same rule, so accepting more here would only defer
+/// the failure to after the single-use token was spent.
+library;
+
+import 'dart:io' show InternetAddress;
+
+class EnrollLink {
+ const EnrollLink({required this.server, required this.token});
+
+ /// Control plane base URL the device enrolls against.
+ final String server;
+
+ /// Bootstrap token spent by POST /enroll.
+ final String token;
+
+ /// Hostname shown to the user before they confirm the enrollment.
+ String get serverHost => Uri.parse(server).host;
+
+ /// Enough of the token to recognise it, never enough to reuse it.
+ String get tokenHint {
+ if (token.length <= 12) return token;
+ return '${token.substring(0, 12)}…';
+ }
+}
+
+/// Parses a `sam://enroll` link; returns null for anything else, including
+/// a bare token, so callers can fall back to token-only entry.
+EnrollLink? parseEnrollLink(String raw) {
+ final Uri uri;
+ try {
+ uri = Uri.parse(raw.trim());
+ } on FormatException {
+ return null;
+ }
+ if (uri.scheme != 'sam' || uri.host != 'enroll') return null;
+ final server = uri.queryParameters['server'] ?? '';
+ final token = uri.queryParameters['token'] ?? '';
+ if (token.isEmpty) return null;
+ if (!isTrustedControlPlaneUrl(server)) return null;
+ return EnrollLink(server: server, token: token);
+}
+
+/// Whether a device may take [server] as its control plane: https, or http
+/// to a loopback host. Same rule as `api.ValidateControlPlaneTransport`.
+bool isTrustedControlPlaneUrl(String server) {
+ final uri = Uri.tryParse(server);
+ if (uri == null || uri.host.isEmpty) return false;
+ switch (uri.scheme) {
+ case 'https':
+ return true;
+ case 'http':
+ return uri.host.toLowerCase() == 'localhost' ||
+ (InternetAddress.tryParse(uri.host)?.isLoopback ?? false);
+ default:
+ return false;
+ }
+}
diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dart
index 19204d54..dcb5a907 100644
--- a/mobile/sam-node-app/lib/main.dart
+++ b/mobile/sam-node-app/lib/main.dart
@@ -16,6 +16,8 @@ import 'package:url_launcher/url_launcher.dart';
import 'sam_ffi.dart';
import 'mcp_server.dart';
+import 'enroll_link.dart';
+import 'scan_page.dart';
// Isolate.run lives in these top-level functions, not in State methods: a closure
// there shares its context with sibling setState closures, so `this` and its
@@ -44,6 +46,14 @@ Future<String?> _isolatedReEnroll(String dataDir, String labelsText) => Isolate.
}
});
+Future<String?> _isolatedEnrollBootstrap(String dataDir, String server, String token, String labelsText) => Isolate.run(() {
+ try {
+ return SamNodeLib().enrollBootstrap(dataDir, server, token, true, labelsText);
+ } catch (e) {
+ return e.toString();
+ }
+});
+
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
@@ -83,6 +93,18 @@ class _NodeControlPageState extends State<NodeControlPage> {
final _jwtController = TextEditingController();
// Saved by the FFI at enrollment so Re-enroll can skip the browser.
String _refreshToken = '';
+ // Bootstrap token typed or pasted by hand; a pasted sam://enroll link is
+ // accepted here too and fills the URL field.
+ final _joinTokenController = TextEditingController();
+ bool _manualEntry = false;
+ // A token-joined node cannot re-attest labels in place: /enroll re-mints
+ // from the labels already on record and there is no login session to
+ // refresh. Re-enroll is disabled for it; the marker dies with the data dir
+ // on unenroll.
+ static const _joinedWithTokenFile = 'joined-with-token';
+ bool _joinedWithToken = false;
+ // sam://enroll links delivered by MainActivity (stock camera app, browser).
+ static const _enrollLinkChannel = MethodChannel('dev.sammesh.connect/enroll_link');
// Bearer token for the sidecar API on 127.0.0.1:5005. Android loopback is
// shared by every installed app, so a fixed value would let any of them
// act as this node. Generated once and kept in the app-private data dir
@@ -96,7 +118,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
static const _labelsFile = 'labels';
final _labelsController = TextEditingController();
- static const _exposeChannel = MethodChannel('com.example.sam_agent/mesh_expose');
+ static const _exposeChannel = MethodChannel('dev.sammesh.connect/mesh_expose');
late SamNodeLib _samLib;
bool?
@@ -135,7 +157,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
void initState() {
super.initState();
_samLib = SamNodeLib();
- _checkEnrollment();
+ _checkEnrollment().then((_) => _listenForEnrollLinks());
_embeddedMcpServer = SamDartMcpServer(
isBatteryEnabled: () => _exposeBattery,
isLocationEnabled: () => _exposeLocation,
@@ -145,8 +167,10 @@ class _NodeControlPageState extends State<NodeControlPage> {
@override
void dispose() {
_pollingTimer?.cancel();
+ _enrollLinkChannel.setMethodCallHandler(null);
_controlPlaneController.dispose();
_jwtController.dispose();
+ _joinTokenController.dispose();
_labelsController.dispose();
_externalMcpUrlController.dispose();
_externalMcpNameController.dispose();
@@ -167,8 +191,10 @@ class _NodeControlPageState extends State<NodeControlPage> {
if (await labelsFile.exists()) {
_labelsController.text = await labelsFile.readAsString();
}
+ final joinedWithToken = await File('$dataDir/$_joinedWithTokenFile').exists();
setState(() {
_isEnrolled = enrolled;
+ _joinedWithToken = joinedWithToken;
if (enrolled) {
_status = 'Enrolled';
// Try to get node ID if running (though might not be started yet)
@@ -730,6 +756,146 @@ class _NodeControlPageState extends State<NodeControlPage> {
});
}
+ // ---- Token / QR enrollment -------------------------------------------
+
+ // Links arrive two ways: the one the activity was launched with (asked for
+ // once, after the enrollment state is known) and later ones pushed while
+ // the app is open.
+ Future<void> _listenForEnrollLinks() async {
+ _enrollLinkChannel.setMethodCallHandler((call) async {
+ if (call.method == 'onLink' && call.arguments is String) {
+ await _handleEnrollLink(call.arguments as String);
+ }
+ });
+ try {
+ final initial = await _enrollLinkChannel.invokeMethod<String>('getInitialLink');
+ if (initial != null) await _handleEnrollLink(initial);
+ } on MissingPluginException {
+ // Not on Android (tests, desktop): links only come from the scanner.
+ } catch (e) {
+ debugPrint('DEBUG: getInitialLink failed: $e');
+ }
+ }
+
+ Future<void> _scanEnrollCode() async {
+ final link = await Navigator.of(context).push<EnrollLink>(
+ MaterialPageRoute(builder: (_) => const ScanEnrollCodePage()),
+ );
+ if (link != null) await _confirmAndEnroll(link);
+ }
+
+ Future<void> _handleEnrollLink(String raw) async {
+ final link = parseEnrollLink(raw);
+ if (link == null) {
+ setState(() => _status = 'Ignored link: not a sam://enroll code');
+ return;
+ }
+ if (_isEnrolled == true) {
+ if (!mounted) return;
+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
+ content: Text('Already enrolled. Unenroll first to join another mesh.')));
+ return;
+ }
+ await _confirmAndEnroll(link);
+ }
+
+ // The link came from a camera or another app: show where it leads before
+ // spending the single-use token on it.
+ Future<void> _confirmAndEnroll(EnrollLink link) async {
+ if (!mounted) return;
+ final ok = await showDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Join this mesh?'),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text('Control plane'),
+ SelectableText(link.server,
+ style: const TextStyle(fontWeight: FontWeight.bold)),
+ const SizedBox(height: 12),
+ const Text('Enrollment token'),
+ Text(link.tokenHint,
+ style: const TextStyle(fontFamily: 'monospace')),
+ const SizedBox(height: 12),
+ const Text(
+ 'Enrollment codes admit a limited number of devices for a '
+ 'limited time. Labels from the Config tab are attested now.',
+ style: TextStyle(fontSize: 12, color: Colors.grey),
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel')),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Join')),
+ ],
+ ),
+ );
+ if (ok == true) await _enrollWithToken(link.server, link.token);
+ }
+
+ // Manual entry: the token field takes either a bare token (with the URL
+ // field naming the control plane) or a whole sam://enroll link.
+ Future<void> _joinWithToken() async {
+ final typed = _joinTokenController.text.trim();
+ if (typed.isEmpty) {
+ setState(() => _status = 'Enter an enrollment token or a sam://enroll link');
+ return;
+ }
+ final link = parseEnrollLink(typed);
+ if (link != null) {
+ _controlPlaneController.text = link.server;
+ await _enrollWithToken(link.server, link.token);
+ return;
+ }
+ final server = _controlPlaneController.text.trim();
+ if (!isTrustedControlPlaneUrl(server)) {
+ setState(() => _status =
+ 'Control plane URL must be https:// (plain http only for localhost)');
+ return;
+ }
+ await _enrollWithToken(server, typed);
+ }
+
+ Future<void> _enrollWithToken(String server, String token) async {
+ final labelsText = _labelsController.text.trim();
+ final labels = _labelsOrReport(labelsText, 'Enrollment failed');
+ if (labels == null) return;
+ setState(() {
+ _loggingIn = true;
+ _status = 'Enrolling with token at ${Uri.parse(server).host}...';
+ });
+ final appDir = await getApplicationDocumentsDirectory();
+ final dataDir = '${appDir.path}/sam_data';
+ final err = await _isolatedEnrollBootstrap(dataDir, server, token, jsonEncode(labels));
+ if (err == null) {
+ await _saveLabels(dataDir, labelsText);
+ try {
+ await File('$dataDir/$_joinedWithTokenFile').create(recursive: true);
+ } catch (e) {
+ debugPrint('DEBUG: Failed to save join marker: $e');
+ }
+ _joinTokenController.clear();
+ }
+ if (!mounted) return;
+ setState(() {
+ _loggingIn = false;
+ if (err != null) {
+ _status = 'Enrollment failed: $err';
+ } else {
+ _controlPlaneController.text = server;
+ _status = 'Enrollment successful!';
+ _isEnrolled = true;
+ _joinedWithToken = true;
+ }
+ });
+ }
+
// Silent path first: the refresh token saved at enrollment buys a JWT.
// Any failure (none saved, expired, revoked) falls back to the browser.
Future<void> _reEnroll() async {
@@ -950,6 +1116,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
}
setState(() {
_isEnrolled = false;
+ _joinedWithToken = false;
_status = 'Unenrolled';
_nodeID = '';
});
@@ -1223,7 +1390,9 @@ class _NodeControlPageState extends State<NodeControlPage> {
if (_isEnrolled == true) ...[
const SizedBox(height: 10),
ElevatedButton.icon(
- onPressed: _loggingIn || isRunning ? null : _reEnroll,
+ onPressed: _loggingIn || isRunning || _joinedWithToken
+ ? null
+ : _reEnroll,
icon: _loggingIn
? const SizedBox(
height: 20,
@@ -1232,6 +1401,14 @@ class _NodeControlPageState extends State<NodeControlPage> {
: const Icon(Icons.login),
label: const Text('Re-enroll to apply'),
),
+ if (_joinedWithToken)
+ const Padding(
+ padding: EdgeInsets.only(top: 6),
+ child: Text(
+ 'Joined with a token. Unenroll and join again to change labels.',
+ style: TextStyle(fontSize: 12, color: Colors.grey),
+ ),
+ ),
],
],
),
@@ -1311,7 +1488,11 @@ class _NodeControlPageState extends State<NodeControlPage> {
);
}
+ // Landing screen. The primary path is the QR code a control plane prints
+ // (sam-one's terminal, `sam-one token qr`); everything else sits behind
+ // "Enter details manually": a bootstrap token, or the OIDC logins.
Widget _buildEnrollmentView() {
+ final busy = _loggingIn;
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
@@ -1320,48 +1501,113 @@ class _NodeControlPageState extends State<NodeControlPage> {
const Text('Welcome to SAM',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
- const SizedBox(height: 20),
- const Text('Please enroll your node to join the mesh.',
- textAlign: TextAlign.center),
- const SizedBox(height: 30),
- TextField(
- controller: _controlPlaneController,
- // A pasted URL often carries a trailing space or newline.
- inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))],
- decoration: const InputDecoration(
- labelText: 'Control plane URL',
- border: OutlineInputBorder(),
- hintText: 'https://bananas.sam-mesh.dev',
- ),
+ const SizedBox(height: 12),
+ const Text(
+ 'Join a mesh by scanning the enrollment code shown by its control plane.',
+ textAlign: TextAlign.center,
),
- const SizedBox(height: 20),
- ElevatedButton.icon(
- onPressed: _loggingIn ? null : _loginAndEnroll,
- icon: _loggingIn
+ const SizedBox(height: 24),
+ FilledButton.icon(
+ onPressed: busy ? null : _scanEnrollCode,
+ icon: busy
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2))
- : const Icon(Icons.login),
- label: const Text('Login & Enroll (Browser)'),
- style: ElevatedButton.styleFrom(
- padding: const EdgeInsets.symmetric(vertical: 16)),
+ : const Icon(Icons.qr_code_scanner),
+ label: const Text('Scan enrollment code'),
+ style: FilledButton.styleFrom(
+ padding: const EdgeInsets.symmetric(vertical: 18)),
),
- const SizedBox(height: 10),
- ElevatedButton.icon(
- onPressed: _loggingIn ? null : _startDeviceLogin,
- icon: const Icon(Icons.tv),
- label: const Text('Device Login (TV / Other Device)'),
- style: ElevatedButton.styleFrom(
- padding: const EdgeInsets.symmetric(vertical: 16)),
+ const SizedBox(height: 8),
+ const Text(
+ 'Opening a sam://enroll link from another app works too.',
+ textAlign: TextAlign.center,
+ style: TextStyle(fontSize: 12, color: Colors.grey),
+ ),
+ const SizedBox(height: 16),
+ TextButton.icon(
+ onPressed: busy
+ ? null
+ : () => setState(() => _manualEntry = !_manualEntry),
+ icon: Icon(_manualEntry ? Icons.expand_less : Icons.expand_more),
+ label: Text(_manualEntry
+ ? 'Hide manual entry'
+ : 'Enter details manually'),
),
- const SizedBox(height: 10),
+ if (_manualEntry) ...[
+ const SizedBox(height: 8),
+ TextField(
+ controller: _controlPlaneController,
+ enabled: !busy,
+ // A pasted URL often carries a trailing space or newline.
+ inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))],
+ decoration: const InputDecoration(
+ labelText: 'Control plane URL',
+ border: OutlineInputBorder(),
+ hintText: 'https://bananas.sam-mesh.dev',
+ ),
+ ),
+ const SizedBox(height: 12),
+ TextField(
+ controller: _joinTokenController,
+ enabled: !busy,
+ inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))],
+ onChanged: (text) {
+ // A pasted sam://enroll link names the control plane itself.
+ final link = parseEnrollLink(text);
+ if (link != null && _controlPlaneController.text != link.server) {
+ setState(() => _controlPlaneController.text = link.server);
+ }
+ },
+ decoration: const InputDecoration(
+ labelText: 'Enrollment token',
+ border: OutlineInputBorder(),
+ hintText: 'sam_dev_… or a sam://enroll link',
+ ),
+ ),
+ const SizedBox(height: 12),
+ ElevatedButton.icon(
+ onPressed: busy ? null : _joinWithToken,
+ icon: const Icon(Icons.vpn_key),
+ label: const Text('Join with token'),
+ style: ElevatedButton.styleFrom(
+ padding: const EdgeInsets.symmetric(vertical: 16)),
+ ),
+ const SizedBox(height: 20),
+ const Row(children: [
+ Expanded(child: Divider()),
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: 12),
+ child: Text('or sign in',
+ style: TextStyle(fontSize: 12, color: Colors.grey)),
+ ),
+ Expanded(child: Divider()),
+ ]),
+ const SizedBox(height: 12),
+ OutlinedButton.icon(
+ onPressed: busy ? null : _loginAndEnroll,
+ icon: const Icon(Icons.login),
+ label: const Text('Login & Enroll (Browser)'),
+ style: OutlinedButton.styleFrom(
+ padding: const EdgeInsets.symmetric(vertical: 16)),
+ ),
+ const SizedBox(height: 10),
+ OutlinedButton.icon(
+ onPressed: busy ? null : _startDeviceLogin,
+ icon: const Icon(Icons.tv),
+ label: const Text('Device Login (TV / Other Device)'),
+ style: OutlinedButton.styleFrom(
+ padding: const EdgeInsets.symmetric(vertical: 16)),
+ ),
+ ],
+ const SizedBox(height: 16),
const Text(
- 'Set labels on the Config tab before enrolling.',
+ 'Labels are attested at enrollment; set them on the Config tab first.',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12, color: Colors.grey),
),
- const SizedBox(height: 30),
+ const SizedBox(height: 24),
if (_status.isNotEmpty &&
_status != 'Enrolled' &&
_status != 'Unenrolled')
diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dart
index afe6f98c..72a1df77 100644
--- a/mobile/sam-node-app/lib/mcp_server.dart
+++ b/mobile/sam-node-app/lib/mcp_server.dart
@@ -5,7 +5,7 @@ import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
class SamDartMcpServer {
- static const MethodChannel _channel = MethodChannel('com.example.sam_agent/mesh_expose');
+ static const MethodChannel _channel = MethodChannel('dev.sammesh.connect/mesh_expose');
HttpServer? _server;
final List<HttpResponse> _sseClients = [];
// Android loopback is shared by every installed app, so the port alone is
diff --git a/mobile/sam-node-app/lib/sam_ffi.dart b/mobile/sam-node-app/lib/sam_ffi.dart
index d8096c79..a358f80c 100644
--- a/mobile/sam-node-app/lib/sam_ffi.dart
+++ b/mobile/sam-node-app/lib/sam_ffi.dart
@@ -33,6 +33,19 @@ typedef ReEnrollNodeC = ffi.Pointer<Utf8> Function(
typedef ReEnrollNodeDart = ffi.Pointer<Utf8> Function(
ffi.Pointer<Utf8> dataDir, ffi.Pointer<Utf8> labels);
+typedef EnrollNodeBootstrapC = ffi.Pointer<Utf8> Function(
+ ffi.Pointer<Utf8> dataDir,
+ ffi.Pointer<Utf8> controlPlaneURL,
+ ffi.Pointer<Utf8> bootstrapToken,
+ ffi.Int8 allowLoopback,
+ ffi.Pointer<Utf8> labels);
+typedef EnrollNodeBootstrapDart = ffi.Pointer<Utf8> Function(
+ ffi.Pointer<Utf8> dataDir,
+ ffi.Pointer<Utf8> controlPlaneURL,
+ ffi.Pointer<Utf8> bootstrapToken,
+ int allowLoopback,
+ ffi.Pointer<Utf8> labels);
+
typedef FetchControlPlaneInfoJSONC = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> controlPlaneURL);
typedef FetchControlPlaneInfoJSONDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> controlPlaneURL);
@@ -52,6 +65,7 @@ class SamNodeLib {
late GetNodeIDDart _getNodeID;
late EnrollNodeDart _enrollNode;
late ReEnrollNodeDart _reEnrollNode;
+ late EnrollNodeBootstrapDart _enrollNodeBootstrap;
late FetchControlPlaneInfoJSONDart _fetchControlPlaneInfoJSON;
late IsEnrolledDart _isEnrolled;
late GetMeshInfoDart _getMeshInfo;
@@ -71,6 +85,7 @@ class SamNodeLib {
_getNodeID = _dylib.lookupFunction<GetNodeIDC, GetNodeIDDart>('GetNodeID');
_enrollNode = _dylib.lookupFunction<EnrollNodeC, EnrollNodeDart>('EnrollNode');
_reEnrollNode = _dylib.lookupFunction<ReEnrollNodeC, ReEnrollNodeDart>('ReEnrollNode');
+ _enrollNodeBootstrap = _dylib.lookupFunction<EnrollNodeBootstrapC, EnrollNodeBootstrapDart>('EnrollNodeBootstrap');
_fetchControlPlaneInfoJSON = _dylib.lookupFunction<FetchControlPlaneInfoJSONC, FetchControlPlaneInfoJSONDart>('FetchControlPlaneInfoJSON');
_isEnrolled = _dylib.lookupFunction<IsEnrolledC, IsEnrolledDart>('IsEnrolled');
_getMeshInfo = _dylib.lookupFunction<GetMeshInfoC, GetMeshInfoDart>('GetMeshInfo');
@@ -142,6 +157,29 @@ class SamNodeLib {
return goErr;
}
+ /// Enrolls with a bootstrap token through POST /enroll; no identity
+ /// provider is involved. A single-use token is burned by this call.
+ String? enrollBootstrap(String dataDir, String controlPlaneURL,
+ String bootstrapToken, bool allowLoopback, String labels) {
+ final cDataDir = dataDir.toNativeUtf8();
+ final cControlPlaneURL = controlPlaneURL.toNativeUtf8();
+ final cToken = bootstrapToken.toNativeUtf8();
+ final cLabels = labels.toNativeUtf8();
+
+ final cErr = _enrollNodeBootstrap(
+ cDataDir, cControlPlaneURL, cToken, allowLoopback ? 1 : 0, cLabels);
+
+ calloc.free(cDataDir);
+ calloc.free(cControlPlaneURL);
+ calloc.free(cToken);
+ calloc.free(cLabels);
+
+ if (cErr.address == 0) return null;
+ final goErr = cErr.toDartString();
+ _freeString(cErr);
+ return goErr;
+ }
+
String? fetchControlPlaneInfoJSON(String controlPlaneURL) {
final cControlPlaneURL = controlPlaneURL.toNativeUtf8();
final cResult = _fetchControlPlaneInfoJSON(cControlPlaneURL);
diff --git a/mobile/sam-node-app/lib/scan_page.dart b/mobile/sam-node-app/lib/scan_page.dart
new file mode 100644
index 00000000..5bd71d90
--- /dev/null
+++ b/mobile/sam-node-app/lib/scan_page.dart
@@ -0,0 +1,90 @@
+import 'package:flutter/material.dart';
+import 'package:mobile_scanner/mobile_scanner.dart';
+
+import 'enroll_link.dart';
+
+/// Full-screen camera view that pops with the first `sam://enroll` link it
+/// sees. Other codes are ignored with a hint rather than returned, so the
+/// caller never has to second-guess the result.
+class ScanEnrollCodePage extends StatefulWidget {
+ const ScanEnrollCodePage({super.key});
+
+ @override
+ State<ScanEnrollCodePage> createState() => _ScanEnrollCodePageState();
+}
+
+class _ScanEnrollCodePageState extends State<ScanEnrollCodePage> {
+ final _controller = MobileScannerController(formats: [BarcodeFormat.qrCode]);
+ bool _done = false;
+ String _hint = 'Point the camera at the enrollment QR code';
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ void _onDetect(BarcodeCapture capture) {
+ if (_done) return;
+ for (final barcode in capture.barcodes) {
+ final raw = barcode.rawValue;
+ if (raw == null) continue;
+ final link = parseEnrollLink(raw);
+ if (link == null) {
+ setState(() => _hint = 'Not a SAM enrollment code');
+ continue;
+ }
+ _done = true;
+ Navigator.of(context).pop(link);
+ return;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Scan enrollment code'),
+ actions: [
+ IconButton(
+ icon: const Icon(Icons.flashlight_on),
+ tooltip: 'Toggle torch',
+ onPressed: () => _controller.toggleTorch(),
+ ),
+ ],
+ ),
+ body: Stack(
+ fit: StackFit.expand,
+ children: [
+ MobileScanner(
+ controller: _controller,
+ onDetect: _onDetect,
+ errorBuilder: (context, error) => Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text(
+ 'Camera unavailable: ${error.errorDetails?.message ?? error.errorCode.name}\n\n'
+ 'Paste the sam://enroll link or the token instead.',
+ textAlign: TextAlign.center,
+ ),
+ ),
+ ),
+ ),
+ Align(
+ alignment: Alignment.bottomCenter,
+ child: Container(
+ width: double.infinity,
+ color: Colors.black54,
+ padding: const EdgeInsets.all(16),
+ child: Text(
+ _hint,
+ textAlign: TextAlign.center,
+ style: const TextStyle(color: Colors.white),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/sam-node-app/pubspec.lock b/mobile/sam-node-app/pubspec.lock
index 28d0b1ab..01e311a0 100644
--- a/mobile/sam-node-app/pubspec.lock
+++ b/mobile/sam-node-app/pubspec.lock
@@ -319,6 +319,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.18.0"
+ mobile_scanner:
+ dependency: "direct main"
+ description:
+ name: mobile_scanner
+ sha256: "5a51ea79f0cf8293f616a5d08baae185b59b5e6bb24df01f2a63037ade0bade0"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.4.2"
objective_c:
dependency: transitive
description:
diff --git a/mobile/sam-node-app/pubspec.yaml b/mobile/sam-node-app/pubspec.yaml
index 5f37192b..fea9c4ec 100644
--- a/mobile/sam-node-app/pubspec.yaml
+++ b/mobile/sam-node-app/pubspec.yaml
@@ -16,6 +16,7 @@ dependencies:
url_launcher: ^6.2.5
crypto: ^3.0.3
qr_flutter: ^4.1.0
+ mobile_scanner: ^7.4.2
firebase_core: ^4.0.0
firebase_ai: ^3.0.0
diff --git a/mobile/sam-node-app/test/enroll_link_test.dart b/mobile/sam-node-app/test/enroll_link_test.dart
new file mode 100644
index 00000000..18df1899
--- /dev/null
+++ b/mobile/sam-node-app/test/enroll_link_test.dart
@@ -0,0 +1,47 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sam_agent/enroll_link.dart';
+
+void main() {
+ // Byte-for-byte the payload sam-one prints under its QR code.
+ const printed =
+ 'sam://enroll?server=https%3A%2F%2Fabc-def-123.trycloudflare.com&token=sam_dev_0123456789abcdef';
+
+ test('parses the link sam-one prints, tolerating pasted whitespace', () {
+ final link = parseEnrollLink(' $printed\n');
+ expect(link, isNotNull);
+ expect(link!.server, 'https://abc-def-123.trycloudflare.com');
+ expect(link.token, 'sam_dev_0123456789abcdef');
+ expect(link.serverHost, 'abc-def-123.trycloudflare.com');
+ expect(link.tokenHint, 'sam_dev_0123…');
+ });
+
+ test('accepts plaintext http only to loopback (emulator over adb reverse)', () {
+ final link = parseEnrollLink(
+ 'sam://enroll?server=http%3A%2F%2F127.0.0.1%3A18432&token=sam-bt-abc');
+ expect(link?.server, 'http://127.0.0.1:18432');
+ expect(link?.serverHost, '127.0.0.1');
+ expect(isTrustedControlPlaneUrl('http://localhost:8080'), isTrue);
+ expect(isTrustedControlPlaneUrl('http://[::1]:8080'), isTrue);
+ expect(isTrustedControlPlaneUrl('http://192.168.1.50:18432'), isFalse);
+ expect(isTrustedControlPlaneUrl('http://mesh.example.com'), isFalse);
+ expect(isTrustedControlPlaneUrl('https://mesh.example.com'), isTrue);
+ });
+
+ test('rejects anything that is not a trustworthy sam://enroll link', () {
+ for (final raw in [
+ 'samone://enroll?server=https%3A%2F%2Fx&token=t',
+ 'sam://join?server=https%3A%2F%2Fx&token=t',
+ 'sam://enroll?server=https%3A%2F%2Fx',
+ 'sam://enroll?token=t',
+ 'sam://enroll?server=ftp%3A%2F%2Fx&token=t',
+ 'sam://enroll?server=x.example.com&token=t',
+ // Plaintext to a LAN host: the FFI would refuse it after burning the token.
+ 'sam://enroll?server=http%3A%2F%2F192.168.1.50%3A18432&token=t',
+ 'sam_dev_0123456789abcdef',
+ 'https://example.com/?token=t',
+ '',
+ ]) {
+ expect(parseEnrollLink(raw), isNull, reason: raw);
+ }
+ });
+}
diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.go
index 2d2939b1..7e5d9f10 100644
--- a/mobile/sam-node-ffi/ffi/ffi.go
+++ b/mobile/sam-node-ffi/ffi/ffi.go
@@ -343,10 +343,39 @@ func decodeLabels(jsonText string) (map[string]string, error) {
return labels, nil
}
-// EnrollNode enrolls a node. Labels arrive as a JSON object and are minted
-// into the node's Biscuit here; changing them means enrolling again, which
-// reuses the stored key so the PeerID survives.
+// EnrollNode enrolls a node with an OIDC JWT. Labels arrive as a JSON object
+// and are minted into the node's Biscuit here; changing them means enrolling
+// again, which reuses the stored key so the PeerID survives.
func EnrollNode(dataDir string, controlPlaneURL string, jwt string, allowLoopback bool, labels string, refreshToken string) error {
+ return enrollWith(dataDir, controlPlaneURL, allowLoopback, labels, func(ctx context.Context, n *node.SamNode, store *node.Store) error {
+ if err := n.Enroll(ctx, controlPlaneURL, jwt); err != nil {
+ return err
+ }
+ if refreshToken != "" {
+ saveRefreshSession(ctx, store, controlPlaneURL, refreshToken)
+ }
+ return nil
+ })
+}
+
+// EnrollNodeBootstrap enrolls a node with a pre-shared bootstrap token (the
+// join token or the one carried by a sam://enroll QR code) through POST
+// /enroll; no identity provider is involved. The control plane spends the
+// token, so a single-use token is burned by this call whether or not the
+// node later keeps its identity.
+func EnrollNodeBootstrap(dataDir string, controlPlaneURL string, bootstrapToken string, allowLoopback bool, labels string) error {
+ if strings.TrimSpace(bootstrapToken) == "" {
+ return errors.New("bootstrap token is required")
+ }
+ return enrollWith(dataDir, controlPlaneURL, allowLoopback, labels, func(ctx context.Context, n *node.SamNode, _ *node.Store) error {
+ return n.EnrollBootstrap(ctx, controlPlaneURL, strings.TrimSpace(bootstrapToken))
+ })
+}
+
+// enrollWith runs one enrollment flow on a throwaway node built from the
+// stored (or freshly generated) key, then persists the control plane URL and
+// syncs the mesh config so the next StartNode finds everything in place.
+func enrollWith(dataDir string, controlPlaneURL string, allowLoopback bool, labels string, enroll func(context.Context, *node.SamNode, *node.Store) error) error {
parsedLabels, err := decodeLabels(labels)
if err != nil {
return err
@@ -406,17 +435,13 @@ func EnrollNode(dataDir string, controlPlaneURL string, jwt string, allowLoopbac
_ = meshNode.Teardown()
}()
- err = meshNode.Enroll(enrollCtx, controlPlaneURL, jwt)
- if err != nil {
+ if err := enroll(enrollCtx, meshNode, store); err != nil {
return fmt.Errorf("enrollment failed: %w", err)
}
if err := store.SaveControlPlaneURL(controlPlaneURL); err != nil {
return fmt.Errorf("failed to save control plane URL: %w", err)
}
- if refreshToken != "" {
- saveRefreshSession(enrollCtx, store, controlPlaneURL, refreshToken)
- }
_, _, _, err = node.SyncMeshConfig(enrollCtx, store)
if err != nil {
diff --git a/mobile/sam-node-ffi/ffi/ffi_test.go b/mobile/sam-node-ffi/ffi/ffi_test.go
index 23c48807..1e312eed 100644
--- a/mobile/sam-node-ffi/ffi/ffi_test.go
+++ b/mobile/sam-node-ffi/ffi/ffi_test.go
@@ -35,19 +35,28 @@ import (
"google.golang.org/protobuf/proto"
)
-func TestMobileFFILifecycle(t *testing.T) {
- // 1. Setup Mock Router
+// mockMesh is a fake control plane plus a router that accepts any auth, so
+// the FFI can enroll and start against it in-process. It records the last
+// request seen on each enrollment endpoint.
+type mockMesh struct {
+ url string
+ registerRequest api.EnrollRequest
+ bootstrapRequest api.BootstrapEnrollRequest
+}
+
+func newMockMesh(t *testing.T) *mockMesh {
+ t.Helper()
routerHost, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))
if err != nil {
t.Fatal(err)
}
- defer func() { _ = routerHost.Close() }()
+ t.Cleanup(func() { _ = routerHost.Close() })
routerDHT, err := dht.New(routerHost, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))
if err != nil {
t.Fatal(err)
}
- defer func() { _ = routerDHT.Close() }()
+ t.Cleanup(func() { _ = routerDHT.Close() })
// Generate key-pair for Mock Control Plane signing
cpPubKey, cpPrivKey, err := ed25519.GenerateKey(rand.Reader)
@@ -74,52 +83,65 @@ func TestMobileFFILifecycle(t *testing.T) {
println("--- MOCK ROUTER: wrote AuthResponse success with valid biscuit")
})
- var enrolledLabels map[string]string
+ mesh := &mockMesh{}
+ routerAddrs := []string{routerHost.Addrs()[0].String() + "/p2p/" + routerHost.ID().String()}
mux := http.NewServeMux()
mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
- var req api.EnrollRequest
- _ = proto.Unmarshal(body, &req)
- enrolledLabels = req.Labels
-
- biscuitBytes := mintMockBiscuit(t, req.PeerId, cpPrivKey, api.RoleNode)
- resp := &api.EnrollResponse{
- BiscuitToken: biscuitBytes,
+ _ = proto.Unmarshal(body, &mesh.registerRequest)
+ writeProto(w, &api.EnrollResponse{
+ BiscuitToken: mintMockBiscuit(t, mesh.registerRequest.PeerId, cpPrivKey, api.RoleNode),
ControlPlanePublicKey: cpPubKey,
- RouterAddresses: []string{routerHost.Addrs()[0].String() + "/p2p/" + routerHost.ID().String()},
- }
- data, _ := proto.Marshal(resp)
- w.Header().Set("Content-Type", "application/x-protobuf")
- _, _ = w.Write(data)
+ RouterAddresses: routerAddrs,
+ })
+ })
+ mux.HandleFunc("/enroll", func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ _ = proto.Unmarshal(body, &mesh.bootstrapRequest)
+ writeProto(w, &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,
+ BiscuitToken: mintMockBiscuit(t, mesh.bootstrapRequest.PeerId, cpPrivKey, api.RoleNode),
+ ControlPlanePublicKey: cpPubKey,
+ RouterAddresses: routerAddrs,
+ })
})
mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
- resp := &api.ControlPlaneInfoResponse{
+ writeProto(w, &api.ControlPlaneInfoResponse{
OidcIssuer: "http://mock-issuer",
ClientId: "mock-client",
Audience: "mock-audience",
- }
- data, _ := proto.Marshal(resp)
- w.Header().Set("Content-Type", "application/x-protobuf")
- _, _ = w.Write(data)
+ })
})
httpServer := httptest.NewServer(mux)
- defer httpServer.Close()
+ t.Cleanup(httpServer.Close)
+ mesh.url = httpServer.URL
+ return mesh
+}
+
+func writeProto(w http.ResponseWriter, message proto.Message) {
+ data, _ := proto.Marshal(message)
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = w.Write(data)
+}
+
+func TestMobileFFILifecycle(t *testing.T) {
+ mesh := newMockMesh(t)
- // 2. Mobile Enrollment
+ // Mobile Enrollment
tmpDir := t.TempDir()
- err = EnrollNode(tmpDir, httpServer.URL, "dummy-jwt", true, `{"region":"eu-west-1"}`, "")
+ err := EnrollNode(tmpDir, mesh.url, "dummy-jwt", true, `{"region":"eu-west-1"}`, "")
if err != nil {
t.Fatalf("EnrollNode failed: %v", err)
}
- if enrolledLabels["region"] != "eu-west-1" {
- t.Fatalf("Expected label region=eu-west-1 in enroll request, got %v", enrolledLabels)
+ if mesh.registerRequest.Labels["region"] != "eu-west-1" {
+ t.Fatalf("Expected label region=eu-west-1 in enroll request, got %v", mesh.registerRequest.Labels)
}
- // 3. Mobile Node Start
+ // Mobile Node Start
cfg := MobileConfig{
DataDir: tmpDir,
- ControlPlaneURL: httpServer.URL,
+ ControlPlaneURL: mesh.url,
MeshID: "test-mesh",
BindAddr: "127.0.0.1:0", // random free port
ApiToken: "test-token",
@@ -146,6 +168,32 @@ func TestMobileFFILifecycle(t *testing.T) {
}
}
+func TestEnrollNodeBootstrap(t *testing.T) {
+ mesh := newMockMesh(t)
+ dir := t.TempDir()
+ if err := EnrollNodeBootstrap(dir, mesh.url, " sam_dev_join-token\n", true, `{"region":"eu-west-1"}`); err != nil {
+ t.Fatalf("EnrollNodeBootstrap failed: %v", err)
+ }
+ if mesh.bootstrapRequest.BootstrapToken != "sam_dev_join-token" {
+ t.Fatalf("bootstrap token not sent (trimmed) to /enroll, got %q", mesh.bootstrapRequest.BootstrapToken)
+ }
+ if mesh.bootstrapRequest.Labels["region"] != "eu-west-1" {
+ t.Fatalf("Expected label region=eu-west-1 in bootstrap request, got %v", mesh.bootstrapRequest.Labels)
+ }
+ if mesh.registerRequest.PeerId != "" {
+ t.Fatal("bootstrap enrollment must not call /register")
+ }
+ if IsEnrolled(dir) != 1 {
+ t.Fatal("expected node to be enrolled after bootstrap enrollment")
+ }
+}
+
+func TestEnrollNodeBootstrapRequiresToken(t *testing.T) {
+ if err := EnrollNodeBootstrap(t.TempDir(), "http://127.0.0.1:1", " ", true, `{}`); err == nil {
+ t.Fatal("expected an empty bootstrap token to be rejected before any network call")
+ }
+}
+
func TestStartNodeRejectsInvalidLabels(t *testing.T) {
if err := StartNode(`{"labels": {"bad key!": "x"}}`); err == nil {
_ = StopNode()
diff --git a/mobile/sam-node-ffi/main.go b/mobile/sam-node-ffi/main.go
index 204a7092..d417116c 100644
--- a/mobile/sam-node-ffi/main.go
+++ b/mobile/sam-node-ffi/main.go
@@ -79,6 +79,15 @@ func ReEnrollNode(dataDir *C.char, labels *C.char) *C.char {
return nil
}
+//export EnrollNodeBootstrap
+func EnrollNodeBootstrap(dataDir *C.char, controlPlaneURL *C.char, bootstrapToken *C.char, allowLoopback C.char, labels *C.char) *C.char {
+ err := ffi.EnrollNodeBootstrap(C.GoString(dataDir), C.GoString(controlPlaneURL), C.GoString(bootstrapToken), allowLoopback != 0, C.GoString(labels))
+ if err != nil {
+ return C.CString(err.Error())
+ }
+ return nil
+}
+
//export FetchControlPlaneInfoJSON
func FetchControlPlaneInfoJSON(controlPlaneURL *C.char) *C.char {
goControlPlaneURL := C.GoString(controlPlaneURL)