From b78a19cbf9dd062b7c4b8820d3dcb4e0f49bd945 Mon Sep 17 00:00:00 2001
From: Matthias Nott <mnott@mnsoft.org>
Date: Wed, 25 Mar 2026 14:33:08 +0100
Subject: [PATCH] fix: add SecurityContext for TLS, fix onBadCertificate type

---
 lib/services/mqtt_service.dart |   17 ++++++++++++++---
 1 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/lib/services/mqtt_service.dart b/lib/services/mqtt_service.dart
index b74b7e1..cb04d2f 100644
--- a/lib/services/mqtt_service.dart
+++ b/lib/services/mqtt_service.dart
@@ -241,11 +241,16 @@
     return null;
   }
 
-  /// Probe a single host:port with a TCP connection attempt (1s timeout).
+  /// Probe a single host:port with a TLS connection attempt (1s timeout).
+  /// Uses SecureSocket since the broker now requires TLS.
   Future<String?> _probeHost(String host, int port) async {
     try {
-      final socket = await Socket.connect(host, port,
-          timeout: const Duration(seconds: 1));
+      final socket = await SecureSocket.connect(
+        host,
+        port,
+        timeout: const Duration(seconds: 1),
+        onBadCertificate: (_) => true, // Accept self-signed cert during scan
+      );
       await socket.close();
       return host;
     } catch (_) {
@@ -262,6 +267,12 @@
       // client.maxConnectionAttempts is final — can't set it
       client.logging(on: false);
 
+      // TLS: broker uses a self-signed certificate.
+      // TODO: pin the cert fingerprint once cert rotation story is defined.
+      client.secure = true;
+      client.securityContext = SecurityContext(withTrustedRoots: true);
+      client.onBadCertificate = (dynamic certificate) => true;
+
       client.onConnected = _onConnected;
       client.onDisconnected = _onDisconnected;
       client.onAutoReconnect = _onAutoReconnect;

--
Gitblit v1.3.1