diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index 73d806a8..8609352a 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -12,8 +12,13 @@ + + + downgrade is performed; a discovered server is only dialled when the + user taps it. Settings warns about cleartext. --> + NSLocalNetworkUsageDescription + Pipelines looks for Pipelines servers on your local network so you can connect without typing an address. + NSBonjourServices + + _pipelines._tcp + CADisableMinimumFrameDurationOnPhone CFBundleDevelopmentRegion diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index a7eecaf6..58571328 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -9,6 +9,7 @@ import '../core/servers/server_catalog.dart'; import '../core/servers/server_catalog_store.dart'; import '../core/servers/server_probe.dart'; import '../core/transport/pipelines_client.dart'; +import '../features/onboarding/discovery/server_discovery.dart'; import '../features/onboarding/onboarding_flow.dart'; import '../features/settings/server_connections.dart'; import '../features/settings/saved_servers_section.dart'; @@ -288,6 +289,7 @@ class _PipelinesRootState extends State { saveServer: _saveOnboardingServer, onDone: _done, savedServers: SavedServersSection(connections: _servers), + discovery: platformServerDiscovery(web: widget.web), serverAddresses: _servers.catalog.active?.endpoints.map(Uri.parse).toList() ?? const [], diff --git a/app/lib/features/onboarding/discovery/bonsoir_server_discovery.dart b/app/lib/features/onboarding/discovery/bonsoir_server_discovery.dart new file mode 100644 index 00000000..43062dd4 --- /dev/null +++ b/app/lib/features/onboarding/discovery/bonsoir_server_discovery.dart @@ -0,0 +1,85 @@ +import 'dart:async'; + +import 'package:bonsoir/bonsoir.dart'; + +import 'discovered_server.dart'; +import 'server_discovery.dart'; + +/// DNS-SD browsing through the platform service: Android NSD (Bonsoir holds +/// the Wi-Fi multicast lock while browsing) and Apple's Network framework +/// (needs NSLocalNetworkUsageDescription and NSBonjourServices). +class BonsoirServerDiscovery implements ServerDiscovery { + BonsoirServerDiscovery({this.type = pipelinesServiceType}); + + final String type; + + @override + Stream> scan() { + late final StreamController> controller; + BonsoirDiscovery? discovery; + StreamSubscription? events; + final found = {}; + + void publish() { + if (!controller.isClosed) controller.add(found.values.toList()); + } + + Future start() async { + try { + final browser = BonsoirDiscovery(type: type); + discovery = browser; + await browser.initialize(); + if (controller.isClosed) return; + events = browser.eventStream?.listen( + (event) { + switch (event) { + case BonsoirDiscoveryServiceFoundEvent(:final service): + unawaited(service.resolve(browser.serviceResolver)); + case BonsoirDiscoveryServiceResolvedEvent(:final service) || + BonsoirDiscoveryServiceUpdatedEvent(:final service): + final server = DiscoveredServer.fromRecord( + instance: service.name, + addresses: service.hostAddresses, + hostname: service.hostname, + port: service.port, + attributes: service.attributes, + ); + if (server != null) { + found[service.name] = server; + publish(); + } + case BonsoirDiscoveryServiceLostEvent(:final service): + if (found.remove(service.name) != null) publish(); + default: + break; + } + }, + onError: (Object error) { + if (!controller.isClosed) controller.addError(error); + }, + ); + await browser.start(); + publish(); + } catch (error, stack) { + if (!controller.isClosed) controller.addError(error, stack); + } + } + + controller = StreamController>( + onListen: () => unawaited(start()), + onCancel: () async { + await events?.cancel(); + final browser = discovery; + if (browser != null && !browser.isStopped) { + try { + await browser.stop(); + } catch (_) { + // Already stopped by the platform; nothing else to release. + } + } + await controller.close(); + }, + ); + return controller.stream; + } +} diff --git a/app/lib/features/onboarding/discovery/discovered_server.dart b/app/lib/features/onboarding/discovery/discovered_server.dart new file mode 100644 index 00000000..63b244c1 --- /dev/null +++ b/app/lib/features/onboarding/discovery/discovered_server.dart @@ -0,0 +1,109 @@ +/// The DNS-SD service type the server advertises (internal/discovery). +const pipelinesServiceType = '_pipelines._tcp'; + +/// A Pipelines server found on the local network. +class DiscoveredServer { + const DiscoveredServer({ + required this.name, + required this.host, + required this.port, + this.secure = false, + this.path = '/connect', + this.passwordRequired = true, + this.version, + }); + + /// Builds a server from a resolved DNS-SD record: the service [instance] + /// name, the resolved [addresses] (and SRV [hostname] when no address is + /// usable), the SRV [port] and the TXT [attributes]. Returns null when there + /// is nothing to dial. + static DiscoveredServer? fromRecord({ + required String instance, + required List addresses, + String? hostname, + required int port, + Map attributes = const {}, + }) { + final host = preferredHost(addresses) ?? _bare(hostname); + if (host == null || port <= 0 || port > 65535) return null; + final path = attributes['path'] ?? ''; + final name = attributes['name'] ?? ''; + return DiscoveredServer( + name: name.isEmpty ? instance : name, + host: host, + port: port, + secure: attributes['tls'] == '1', + path: path.startsWith('/') ? path : '/connect', + passwordRequired: attributes['auth'] != 'none', + version: attributes['v'], + ); + } + + final String name; + final String host; + final int port; + final bool secure; + final String path; + final bool passwordRequired; + final String? version; + + /// The websocket endpoint the connect screen dials. + Uri get endpoint => + Uri(scheme: secure ? 'wss' : 'ws', host: host, port: port, path: path); + + /// "host:port" as shown under the name. + String get address => endpoint.authority; + + /// Picks the address a phone can dial: IPv4 first, then a routable IPv6 + /// address. Link-local IPv6 needs a zone the URL cannot carry. + static String? preferredHost(List addresses) { + final values = [for (final value in addresses) value.trim()]; + for (final value in values) { + final bytes = _ipv4(value); + if (bytes != null && bytes[0] != 127) return value; + } + for (final value in values) { + final bytes = _ipv6(value); + if (bytes == null) continue; + final loopback = + bytes.sublist(0, 15).every((byte) => byte == 0) && bytes[15] == 1; + final linkLocal = bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80; + if (!loopback && !linkLocal) return value; + } + return null; + } + + static List? _ipv4(String value) { + if (!RegExp(r'^\d{1,3}(\.\d{1,3}){3}$').hasMatch(value)) return null; + try { + return Uri.parseIPv4Address(value); + } on FormatException { + return null; + } + } + + static List? _ipv6(String value) { + if (!value.contains(':') || value.contains('%')) return null; + try { + return Uri.parseIPv6Address(value); + } on FormatException { + return null; + } + } + + static String? _bare(String? hostname) { + final value = hostname?.trim().replaceFirst(RegExp(r'\.$'), '') ?? ''; + return value.isEmpty ? null : value; + } + + @override + bool operator ==(Object other) => + other is DiscoveredServer && + other.name == name && + other.endpoint == endpoint && + other.passwordRequired == passwordRequired && + other.version == version; + + @override + int get hashCode => Object.hash(name, endpoint, passwordRequired, version); +} diff --git a/app/lib/features/onboarding/discovery/discovery_panel.dart b/app/lib/features/onboarding/discovery/discovery_panel.dart new file mode 100644 index 00000000..8010a3e7 --- /dev/null +++ b/app/lib/features/onboarding/discovery/discovery_panel.dart @@ -0,0 +1,197 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'discovered_server.dart'; +import 'server_discovery.dart'; + +enum _Phase { idle, scanning, done, failed } + +/// "Find servers on this network": browses for a while, lists what answered +/// and hands a tapped server to [onSelect]. Manual entry stays beside it. +class DiscoveryPanel extends StatefulWidget { + const DiscoveryPanel({ + super.key, + required this.discovery, + required this.onSelect, + this.enabled = true, + this.scanFor = const Duration(seconds: 8), + }); + + final ServerDiscovery discovery; + final ValueChanged onSelect; + final bool enabled; + + /// How long one scan browses before it settles on its results. + final Duration scanFor; + + @override + State createState() => _DiscoveryPanelState(); +} + +class _DiscoveryPanelState extends State { + _Phase _phase = _Phase.idle; + List _servers = const []; + String? _error; + StreamSubscription>? _scan; + Timer? _timer; + + @override + void dispose() { + _stop(); + super.dispose(); + } + + void _stop() { + _timer?.cancel(); + _timer = null; + unawaited(_scan?.cancel()); + _scan = null; + } + + void _start() { + _stop(); + setState(() { + _phase = _Phase.scanning; + _servers = const []; + _error = null; + }); + _scan = widget.discovery.scan().listen( + (servers) { + if (mounted) setState(() => _servers = servers); + }, + onError: (Object error) { + _stop(); + if (mounted) { + setState(() { + _phase = _Phase.failed; + _error = '$error'; + }); + } + }, + ); + _timer = Timer(widget.scanFor, () { + _stop(); + if (mounted) setState(() => _phase = _Phase.done); + }); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final scanning = _phase == _Phase.scanning; + final label = _phase == _Phase.idle + ? 'Find servers on this network' + : 'Search again'; + final enabled = widget.enabled && !scanning; + final button = cupertino + ? CupertinoButton( + key: const Key('discovery-scan'), + onPressed: enabled ? _start : null, + child: Text(label), + ) + : OutlinedButton.icon( + key: const Key('discovery-scan'), + onPressed: enabled ? _start : null, + icon: const Icon(Icons.wifi_find), + label: Text(label), + ); + final status = switch (_phase) { + _Phase.scanning => _status( + context, + cupertino, + const Key('discovery-scanning'), + 'Looking for Pipelines servers…', + busy: true, + ), + _Phase.done when _servers.isEmpty => _status( + context, + cupertino, + const Key('discovery-empty'), + 'No Pipelines servers answered on this network. ' + 'Enter the address instead.', + ), + _Phase.failed => _status( + context, + cupertino, + const Key('discovery-error'), + 'Could not search this network: $_error', + error: true, + ), + _ => null, + }; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + button, + ?status, + for (final server in _servers) _row(context, cupertino, server), + ], + ); + } + + Widget _status( + BuildContext context, + bool cupertino, + Key key, + String text, { + bool busy = false, + bool error = false, + }) { + final color = !error + ? null + : cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + return Padding( + key: key, + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + if (busy) ...[ + cupertino + ? const CupertinoActivityIndicator() + : const SizedBox.square( + dimension: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 12), + ], + Expanded( + child: Text(text, style: TextStyle(color: color)), + ), + ], + ), + ); + } + + Widget _row(BuildContext context, bool cupertino, DiscoveredServer server) { + final key = Key('discovered-${server.address}'); + final subtitle = Text( + server.passwordRequired ? '${server.address} · password' : server.address, + ); + void tap() => widget.onSelect(server); + final onTap = widget.enabled ? tap : null; + if (cupertino) { + return CupertinoListTile( + key: key, + leading: const Icon(CupertinoIcons.desktopcomputer), + title: Text(server.name), + subtitle: subtitle, + trailing: const CupertinoListTileChevron(), + onTap: onTap, + ); + } + return ListTile( + key: key, + leading: const Icon(Icons.dns_outlined), + title: Text(server.name), + subtitle: subtitle, + trailing: const Icon(Icons.chevron_right), + enabled: widget.enabled, + onTap: onTap, + ); + } +} diff --git a/app/lib/features/onboarding/discovery/server_discovery.dart b/app/lib/features/onboarding/discovery/server_discovery.dart new file mode 100644 index 00000000..3e8d41ac --- /dev/null +++ b/app/lib/features/onboarding/discovery/server_discovery.dart @@ -0,0 +1,18 @@ +import 'package:flutter/foundation.dart'; + +import 'bonsoir_server_discovery.dart'; +import 'discovered_server.dart'; + +/// Finds Pipelines servers on the local network. +abstract interface class ServerDiscovery { + /// Browses while listened to. Each event is every server currently known; + /// a failure to browse is a stream error. Cancelling stops the browse. + Stream> scan(); +} + +/// The discovery this platform supports, or null where there is none. +/// +/// Browsers cannot send mDNS, and the web app is served by the server it +/// talks to, so web has no scan. +ServerDiscovery? platformServerDiscovery({bool web = kIsWeb}) => + web ? null : BonsoirServerDiscovery(); diff --git a/app/lib/features/onboarding/onboarding_flow.dart b/app/lib/features/onboarding/onboarding_flow.dart index f453cfd7..d0954f52 100644 --- a/app/lib/features/onboarding/onboarding_flow.dart +++ b/app/lib/features/onboarding/onboarding_flow.dart @@ -5,6 +5,9 @@ import '../../core/session/server_session.dart'; import '../../core/transport/server_url.dart'; import '../../core/servers/server_probe.dart'; import '../../ui/adaptive/host.dart'; +import 'discovery/discovered_server.dart'; +import 'discovery/discovery_panel.dart'; +import 'discovery/server_discovery.dart'; /// Reaches a server and reports what it says about this device's session. typedef ServerCheck = Future Function(Uri endpoint); @@ -25,6 +28,7 @@ class OnboardingFlow extends StatefulWidget { this.saveServer, this.savedServers, this.serverAddresses = const [], + this.discovery, }); /// Called with the signed-in server's endpoint. @@ -41,6 +45,9 @@ class OnboardingFlow extends StatefulWidget { final Widget? savedServers; final List serverAddresses; + /// LAN discovery; null hides the scan (web, or no platform support). + final ServerDiscovery? discovery; + @override State createState() => _OnboardingFlowState(); } @@ -135,6 +142,11 @@ class _OnboardingFlowState extends State { }); } + void _useDiscovered(DiscoveredServer server) { + _server.text = server.endpoint.toString(); + _continue(); + } + Future _signIn() async { final endpoint = _endpoint; if (endpoint == null || _password.text.isEmpty) return; @@ -239,6 +251,14 @@ class _OnboardingFlowState extends State { ], const SizedBox(height: 16), button, + if (!_passwordStep && widget.discovery != null) ...[ + const SizedBox(height: 16), + DiscoveryPanel( + discovery: widget.discovery!, + enabled: !_busy, + onSelect: _useDiscovered, + ), + ], if (_passwordStep && !widget.startAtPassword) ...[ const SizedBox(height: 8), cupertino diff --git a/app/pubspec.lock b/app/pubspec.lock index f2f3fca9..e0f9bedd 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -25,6 +25,54 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + bonsoir: + dependency: "direct main" + description: + name: bonsoir + sha256: "20fed01e4616e625f4bafd9007ff899d231d8d79bebc8564853fa1e3570294a6" + url: "https://pub.dev" + source: hosted + version: "7.1.5" + bonsoir_android: + dependency: transitive + description: + name: bonsoir_android + sha256: "0dda1164e826553b8ee90a3fd1aabd462d17f19348f542b95f9d5b5455e4157f" + url: "https://pub.dev" + source: hosted + version: "7.1.3" + bonsoir_darwin: + dependency: transitive + description: + name: bonsoir_darwin + sha256: "6f695a0b4465514b75fc1a457746ab6dfc10d7180f0d04810fd9512e6520df69" + url: "https://pub.dev" + source: hosted + version: "7.1.1" + bonsoir_linux: + dependency: transitive + description: + name: bonsoir_linux + sha256: "9afae7bb9509c5bd20a0ea2ca02a0f2b1ef09cca1ceb2ea288ed58a0f03d1e11" + url: "https://pub.dev" + source: hosted + version: "7.1.0" + bonsoir_platform_interface: + dependency: transitive + description: + name: bonsoir_platform_interface + sha256: "6c55c786b01ad279f675ae72cea3a885aa746e416d2e8c1f0c46e9d2c06420b0" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + bonsoir_windows: + dependency: transitive + description: + name: bonsoir_windows + sha256: aaabbb652fe68d3eb26a9b2cddefaae26cd9ca6ebe737d476ab9ed535c7c2516 + url: "https://pub.dev" + source: hosted + version: "7.3.0" boolean_selector: dependency: transitive description: @@ -101,10 +149,10 @@ packages: dependency: transitive description: name: dbus - sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 + sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383 url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.7.15" fake_async: dependency: transitive description: @@ -157,10 +205,10 @@ packages: dependency: transitive description: name: file_picker_linux - sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da + sha256: eb00de71b123e91d3c61f389a05b8cc90f9cbe7e4c88da30ebe2f0442b281b61 url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "2.0.3" file_picker_platform_interface: dependency: transitive description: diff --git a/app/pubspec.yaml b/app/pubspec.yaml index f41f9a93..a1e6e95e 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -48,6 +48,7 @@ dependencies: share_plus: ^13.3.1 file_picker: ^13.3.0 url_launcher: ^6.3.3 + bonsoir: ^7.1.5 dev_dependencies: flutter_test: diff --git a/app/test/features/onboarding/discovery/discovered_server_test.dart b/app/test/features/onboarding/discovery/discovered_server_test.dart new file mode 100644 index 00000000..9f2d7099 --- /dev/null +++ b/app/test/features/onboarding/discovery/discovered_server_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/onboarding/discovery/discovered_server.dart'; +import 'package:pipelines_app/features/onboarding/discovery/server_discovery.dart'; + +void main() { + test('a proxied server becomes a ws endpoint that asks for a password', () { + final server = DiscoveredServer.fromRecord( + instance: 'Pipelines-box', + addresses: ['fe80::1', '192.168.1.20'], + port: 8083, + attributes: { + 'v': 'v1.4.0', + 'name': 'box', + 'path': '/connect', + 'tls': '0', + 'auth': 'password', + }, + )!; + expect(server.name, 'box'); + expect(server.endpoint, Uri.parse('ws://192.168.1.20:8083/connect')); + expect(server.address, '192.168.1.20:8083'); + expect(server.passwordRequired, isTrue); + expect(server.version, 'v1.4.0'); + }); + + test('TLS, no auth, missing TXT and IPv6-only records', () { + final secure = DiscoveredServer.fromRecord( + instance: 'Pipelines-box', + addresses: ['2001:db8::5'], + port: 443, + attributes: {'tls': '1', 'auth': 'none'}, + )!; + expect(secure.name, 'Pipelines-box'); + expect(secure.endpoint, Uri.parse('wss://[2001:db8::5]:443/connect')); + expect(secure.passwordRequired, isFalse); + }); + + test('falls back to the SRV host name, and refuses nothing to dial', () { + final named = DiscoveredServer.fromRecord( + instance: 'Pipelines-box', + addresses: ['fe80::1', '127.0.0.1'], + hostname: 'box.local.', + port: 8083, + )!; + expect(named.endpoint, Uri.parse('ws://box.local:8083/connect')); + expect( + DiscoveredServer.fromRecord( + instance: 'x', + addresses: const [], + port: 8083, + ), + isNull, + ); + expect( + DiscoveredServer.fromRecord( + instance: 'x', + addresses: ['10.0.0.2'], + port: 0, + ), + isNull, + ); + }); + + test('web has no discovery; native platforms do', () { + expect(platformServerDiscovery(web: true), isNull); + expect(platformServerDiscovery(web: false), isNotNull); + }); +} diff --git a/app/test/features/onboarding/discovery/discovery_panel_test.dart b/app/test/features/onboarding/discovery/discovery_panel_test.dart new file mode 100644 index 00000000..b95650b6 --- /dev/null +++ b/app/test/features/onboarding/discovery/discovery_panel_test.dart @@ -0,0 +1,164 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/features/onboarding/discovery/discovered_server.dart'; +import 'package:pipelines_app/features/onboarding/discovery/server_discovery.dart'; +import 'package:pipelines_app/features/onboarding/onboarding_flow.dart'; + +/// A discoverer the test drives: each scan is a controller the test feeds. +class FakeDiscovery implements ServerDiscovery { + final scans = >>[]; + int cancelled = 0; + + StreamController> get current => scans.last; + + @override + Stream> scan() { + final controller = StreamController>( + onCancel: () => cancelled++, + ); + scans.add(controller); + return controller.stream; + } +} + +const box = DiscoveredServer(name: 'box', host: '192.168.1.20', port: 8083); +const studio = DiscoveredServer( + name: 'studio', + host: '192.168.1.30', + port: 8080, + passwordRequired: false, +); + +Widget host(Widget child, {bool cupertino = false}) => + cupertino ? CupertinoApp(home: child) : MaterialApp(home: child); + +void main() { + late FakeDiscovery discovery; + late List checked; + late List saved; + + setUp(() { + discovery = FakeDiscovery(); + checked = []; + saved = []; + }); + + OnboardingFlow flow({ServerDiscovery? discoverer, ValueChanged? done}) => + OnboardingFlow( + discovery: discoverer, + check: (uri) async { + checked.add(uri); + return SessionState.signedOut; + }, + saveServer: (url) async => saved.add(url), + onDone: done ?? (_) {}, + ); + + testWidgets('no discoverer (web) shows manual entry only', (tester) async { + await tester.pumpWidget(host(flow())); + expect(find.byKey(const Key('onboarding-server')), findsOneWidget); + expect(find.byKey(const Key('discovery-scan')), findsNothing); + }); + + testWidgets('scanning lists servers as they answer, then settles', ( + tester, + ) async { + await tester.pumpWidget(host(flow(discoverer: discovery))); + expect(find.text('Find servers on this network'), findsOneWidget); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + expect(find.byKey(const Key('discovery-scanning')), findsOneWidget); + + discovery.current.add([box]); + await tester.pump(); + expect(find.text('box'), findsOneWidget); + expect(find.text('192.168.1.20:8083 · password'), findsOneWidget); + + discovery.current.add([box, studio]); + await tester.pump(); + expect(find.text('studio'), findsOneWidget); + expect(find.text('192.168.1.30:8080'), findsOneWidget); + + await tester.pump(const Duration(seconds: 8)); + expect(find.byKey(const Key('discovery-scanning')), findsNothing); + expect(discovery.cancelled, 1); + expect(find.text('box'), findsOneWidget); + expect(find.text('Search again'), findsOneWidget); + }); + + testWidgets('tapping a server fills the address and connects', ( + tester, + ) async { + await tester.pumpWidget(host(flow(discoverer: discovery))); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.add([box]); + await tester.pump(); + await tester.tap(find.byKey(const Key('discovered-192.168.1.20:8083'))); + await tester.pumpAndSettle(); + + final endpoint = Uri.parse('ws://192.168.1.20:8083/connect'); + expect(checked, [endpoint]); + expect(saved, [endpoint.toString()]); + // The server wants its password: the flow moved to sign-in. + expect(find.byKey(const Key('onboarding-password')), findsOneWidget); + expect(find.byKey(const Key('discovery-scan')), findsNothing); + }); + + testWidgets('an empty scan says so and keeps manual entry', (tester) async { + await tester.pumpWidget(host(flow(discoverer: discovery))); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.add(const []); + await tester.pump(const Duration(seconds: 8)); + expect(find.byKey(const Key('discovery-empty')), findsOneWidget); + expect(find.byKey(const Key('onboarding-server')), findsOneWidget); + + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + expect(discovery.scans, hasLength(2)); + expect(find.byKey(const Key('discovery-empty')), findsNothing); + expect(find.byKey(const Key('discovery-scanning')), findsOneWidget); + await tester.pump(const Duration(seconds: 8)); + }); + + testWidgets('a browse failure is shown and the scan can be retried', ( + tester, + ) async { + await tester.pumpWidget(host(flow(discoverer: discovery))); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.addError(StateError('multicast blocked')); + await tester.pump(); + expect(find.byKey(const Key('discovery-error')), findsOneWidget); + expect(find.textContaining('multicast blocked'), findsOneWidget); + expect(find.byKey(const Key('discovery-scanning')), findsNothing); + // The timer was cancelled with the scan; nothing fires later. + await tester.pump(const Duration(seconds: 8)); + expect(find.byKey(const Key('discovery-error')), findsOneWidget); + }); + + testWidgets('Cupertino host lists and connects the same way', (tester) async { + await tester.pumpWidget(host(flow(discoverer: discovery), cupertino: true)); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.add([studio]); + await tester.pump(); + expect(find.byType(CupertinoListTile), findsOneWidget); + await tester.tap(find.byKey(const Key('discovered-192.168.1.30:8080'))); + await tester.pumpAndSettle(); + expect(checked, [Uri.parse('ws://192.168.1.30:8080/connect')]); + }); + + testWidgets('leaving the screen mid-scan stops browsing', (tester) async { + await tester.pumpWidget(host(flow(discoverer: discovery))); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + await tester.pumpWidget(host(const SizedBox())); + expect(discovery.cancelled, 1); + }); +} diff --git a/cmd/pipelines-server/main.go b/cmd/pipelines-server/main.go index 59c3d648..b5d86fe8 100644 --- a/cmd/pipelines-server/main.go +++ b/cmd/pipelines-server/main.go @@ -13,6 +13,7 @@ import ( "time" "git.a-wan.net/alan/pipelines/internal/buildinfo" + "git.a-wan.net/alan/pipelines/internal/discovery" "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/paths" "git.a-wan.net/alan/pipelines/internal/pipeline" @@ -34,6 +35,8 @@ func main() { log.Fatal(err) } db := flag.String("db", defaultDB, "SQLite database path (honors XDG_DATA_HOME)") + mdnsOn := flag.Bool("mdns", envEnabled(os.Getenv("PIPELINES_MDNS")), "Advertise the server on the LAN with mDNS/DNS-SD ("+discovery.ServiceType+"); PIPELINES_MDNS=off disables") + mdnsPort := flag.Int("mdns-port", envPort(os.Getenv("PIPELINES_MDNS_PORT")), "Port LAN clients dial: the authenticated web proxy fronting this server (default: the -addr port when it is not loopback)") flag.Parse() if err := os.MkdirAll(filepath.Dir(*db), 0700); err != nil { log.Fatal(err) @@ -147,6 +150,11 @@ func main() { if len(chats.Backends()) > 0 { chatNames = chats.Backends() } + if *mdnsOn { + if stopMDNS := advertise(*addr, *mdnsPort); stopMDNS != nil { + defer stopMDNS() + } + } printBanner(startup{Build: buildinfo.Current(), Addr: *addr, Database: *db, Artifacts: artifactsRoot, Authoring: *allowAuthoring, OpenCode: openCodeStatus, Chat: chatNames}) log.Printf("listening on %s (WebSocket endpoint: /connect)", *addr) diff --git a/cmd/pipelines-server/mdns.go b/cmd/pipelines-server/mdns.go new file mode 100644 index 00000000..4637b083 --- /dev/null +++ b/cmd/pipelines-server/mdns.go @@ -0,0 +1,50 @@ +package main + +import ( + "log" + "os" + "strconv" + "strings" + + "git.a-wan.net/alan/pipelines/internal/buildinfo" + "git.a-wan.net/alan/pipelines/internal/discovery" +) + +// advertise publishes the server on the LAN. Any failure is logged and the +// server carries on: discovery is a convenience, never a startup requirement. +// The returned stop (nil when nothing was published) withdraws the advert. +func advertise(addr string, proxyPort int) func() { + hostname, _ := os.Hostname() + advert, err := discovery.Plan(discovery.Config{ListenAddr: addr, ProxyPort: proxyPort, + Version: buildinfo.Current().Version, Hostname: hostname, IPs: discovery.LANAddresses()}) + if err != nil { + log.Printf("mDNS: not advertising: %v", err) + return nil + } + stop, err := discovery.Start(advert, log.Default()) + if err != nil { + log.Printf("mDNS: advertising failed: %v", err) + return nil + } + log.Printf("mDNS: advertising %s.%s on port %d (%s)", advert.Instance, discovery.ServiceType, advert.Port, strings.Join(advert.TXT, " ")) + return stop +} + +// envEnabled reads PIPELINES_MDNS: unset or anything but an explicit off value +// leaves advertising on. +func envEnabled(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "0", "false", "off", "no", "disabled": + return false + } + return true +} + +// envPort reads PIPELINES_MDNS_PORT; anything unusable means "not set". +func envPort(value string) int { + port, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil || port < 0 || port > 65535 { + return 0 + } + return port +} diff --git a/cmd/pipelines-server/mdns_test.go b/cmd/pipelines-server/mdns_test.go new file mode 100644 index 00000000..1aef770f --- /dev/null +++ b/cmd/pipelines-server/mdns_test.go @@ -0,0 +1,25 @@ +package main + +import "testing" + +func TestMDNSEnvironmentSwitches(t *testing.T) { + for value, want := range map[string]bool{"": true, "1": true, "on": true, "off": false, "0": false, "FALSE": false, " disabled ": false} { + if got := envEnabled(value); got != want { + t.Errorf("envEnabled(%q) = %v, want %v", value, got, want) + } + } + for value, want := range map[string]int{"": 0, "8083": 8083, "x": 0, "70000": 0} { + if got := envPort(value); got != want { + t.Errorf("envPort(%q) = %d, want %d", value, got, want) + } + } +} + +// A loopback-only server with no proxy port publishes nothing and does not +// fail: the caller only defers a non-nil stop. +func TestAdvertiseSkipsLoopbackWithoutFailing(t *testing.T) { + if stop := advertise("127.0.0.1:0", 0); stop != nil { + stop() + t.Fatal("loopback-only server was advertised") + } +} diff --git a/docs/install.md b/docs/install.md index e24b2287..24603117 100644 --- a/docs/install.md +++ b/docs/install.md @@ -94,6 +94,14 @@ Expose only the web proxy. A reinstall keeps the saved ports and bind addresses unless you pass the flag again, so an installation set up with `--web-port 8083` stays on 8083. +The server advertises itself on the LAN with mDNS/DNS-SD as `_pipelines._tcp`, +so the phone app's "Find servers on this network" lists it. The advertised port +is the web proxy's (when it listens beyond loopback; the supervisor passes +`-mdns-port`), or the server's own `-addr` port when that is a LAN address. +TXT records: `v` (version), `name` (host), `path=/connect`, `tls=0`, +`auth=password|none`. Set `PIPELINES_MDNS=off` (or `-mdns=false`) to disable +it; a failure to advertise is logged and never stops the server. + `PIPELINES_WEB_PUBLIC_URL` is the address phones and notification links use. Set it once; reinstalls keep it: @@ -253,7 +261,7 @@ go run ./cmd/pipelines --url ws://127.0.0.1:8081/connect tui ``` `go run ./cmd/pipelines-server -help` lists the server flags (`-addr`, `-db`, -`-allow-authoring`, `-opencode-endpoint`). Without `-db` it uses the standard +`-allow-authoring`, `-opencode-endpoint`, `-mdns`, `-mdns-port`). Without `-db` it uses the standard per-user data directory (`XDG_DATA_HOME`, or Application Support on macOS). ## Troubleshooting diff --git a/go.mod b/go.mod index ee07ad38..701a06ba 100644 --- a/go.mod +++ b/go.mod @@ -3,25 +3,29 @@ module git.a-wan.net/alan/pipelines go 1.27.0 require ( + github.com/atotto/clipboard v0.1.4 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/glamour v0.10.0 github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 github.com/charmbracelet/x/ansi v0.10.1 github.com/coder/websocket v1.8.15 + github.com/hashicorp/mdns v1.0.7 + github.com/miekg/dns v1.1.72 + github.com/muesli/termenv v0.16.0 github.com/pmezard/go-difflib v1.0.0 github.com/sahilm/fuzzy v0.1.1 github.com/yuin/goldmark v1.7.8 - golang.org/x/term v0.31.0 + golang.org/x/sys v0.48.0 + golang.org/x/term v0.46.0 modernc.org/sqlite v1.60.1 ) require ( github.com/alecthomas/chroma/v2 v2.14.0 // indirect - github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/glamour v0.10.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect github.com/charmbracelet/x/term v0.2.1 // indirect @@ -38,15 +42,16 @@ require ( github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/reflow v0.3.0 // indirect - github.com/muesli/termenv v0.16.0 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect - golang.org/x/net v0.33.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/text v0.24.0 // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/net v0.59.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/text v0.42.0 // indirect + golang.org/x/tools v0.50.0 // indirect modernc.org/libc v1.77.1 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect diff --git a/go.sum b/go.sum index 4793ec97..baa77c26 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,11 @@ +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= +github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= @@ -16,14 +22,10 @@ github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4p github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= @@ -40,6 +42,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -48,6 +52,10 @@ github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hashicorp/mdns v1.0.7 h1:yWoQVMW5JOiDxQnIUcm3IDt0kCjf3TuXHDbdEKPsbAY= +github.com/hashicorp/mdns v1.0.7/go.mod h1:yjuhYhZyPDqXXL48xC7cdpGwGUMwu7OViDmsuT5COvg= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= @@ -61,6 +69,8 @@ github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6T github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk= github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= +github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= +github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= @@ -92,19 +102,17 @@ golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZ golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= -golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= -golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= -golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= +golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg= diff --git a/internal/discovery/advertise.go b/internal/discovery/advertise.go new file mode 100644 index 00000000..a544c42a --- /dev/null +++ b/internal/discovery/advertise.go @@ -0,0 +1,178 @@ +// Package discovery advertises the Pipelines server on the local network with +// mDNS/DNS-SD (Bonjour), so a phone on the same LAN can find it without typing +// an address. +// +// The advertised port is the one a LAN client dials. The installed server binds +// loopback behind the authenticated web proxy, so the installer passes the +// proxy's port (-mdns-port); a server bound to a LAN address with no proxy +// advertises its own listen port and no authentication. +package discovery + +import ( + "errors" + "fmt" + "log" + "net" + "strconv" + "strings" + + "github.com/hashicorp/mdns" +) + +// ServiceType is the DNS-SD service type clients browse for. +const ServiceType = "_pipelines._tcp" + +// Config is what the server knows about how LAN clients reach it. +type Config struct { + // ListenAddr is the server's own -addr. + ListenAddr string + // ProxyPort, when non-zero, is the port of the authenticated web proxy on + // this host that fronts the server for LAN clients. + ProxyPort int + // Version is the server build version. + Version string + // Hostname is this machine's host name (os.Hostname). + Hostname string + // IPs are the LAN addresses clients may dial. + IPs []net.IP +} + +// Advert is the record set the server publishes. +type Advert struct { + Instance string + Host string // fully qualified, e.g. "box.local." + Port int + IPs []net.IP + TXT []string +} + +// ErrNotReachable means no LAN client could dial what the server would +// advertise (loopback-only listener without a proxy, or no LAN address). +var ErrNotReachable = errors.New("not reachable from the LAN") + +// Plan decides what to advertise. It is pure, so tests check record content +// without touching the network. +func Plan(cfg Config) (Advert, error) { + port, auth := cfg.ProxyPort, "password" + if port == 0 { + host, value, err := net.SplitHostPort(cfg.ListenAddr) + if err != nil { + return Advert{}, fmt.Errorf("listen address %q: %w", cfg.ListenAddr, err) + } + if ip := net.ParseIP(host); host == "localhost" || (ip != nil && ip.IsLoopback()) { + return Advert{}, fmt.Errorf("server listens on loopback %s and no -mdns-port names its LAN proxy: %w", cfg.ListenAddr, ErrNotReachable) + } + if port, err = strconv.Atoi(value); err != nil || port <= 0 { + return Advert{}, fmt.Errorf("listen address %q has no usable port: %w", cfg.ListenAddr, ErrNotReachable) + } + auth = "none" + } + if port <= 0 || port > 65535 { + return Advert{}, fmt.Errorf("advertised port %d is out of range", port) + } + if len(cfg.IPs) == 0 { + return Advert{}, fmt.Errorf("no LAN IPv4 address: %w", ErrNotReachable) + } + label := hostLabel(cfg.Hostname) + version := cfg.Version + if version == "" { + version = "dev" + } + return Advert{ + Instance: "Pipelines-" + label, + Host: label + ".local.", + Port: port, + IPs: cfg.IPs, + // TXT keys follow RFC 6763 (short, lower case). The scheme and path are + // what the client puts in its ws(s):// URL. + TXT: []string{ + "v=" + version, + "name=" + label, + "path=/connect", + "tls=0", + "auth=" + auth, + }, + }, nil +} + +// hostLabel reduces a host name to one DNS label: the first dotted part, with +// anything other than letters, digits and hyphens replaced, so instance and +// host names never need escaping on the wire. +func hostLabel(hostname string) string { + first, _, _ := strings.Cut(strings.TrimSpace(hostname), ".") + var b strings.Builder + for _, r := range first { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-': + b.WriteRune(r) + default: + b.WriteRune('-') + } + } + label := strings.Trim(b.String(), "-") + if label == "" { + return "pipelines" + } + if len(label) > 50 { + label = label[:50] + } + return label +} + +// Zone builds the DNS-SD zone that answers queries for the advert. +func (a Advert) Zone() (*mdns.MDNSService, error) { + return mdns.NewMDNSService(a.Instance, ServiceType, "local.", a.Host, a.Port, a.IPs, a.TXT) +} + +// Start publishes the advert until the returned stop is called. Failure is an +// error for the caller to log; it never blocks startup. +func Start(a Advert, logger *log.Logger) (stop func(), err error) { + zone, err := a.Zone() + if err != nil { + return nil, err + } + server, err := mdns.NewServer(&mdns.Config{Zone: zone, Logger: logger}) + if err != nil { + return nil, err + } + return func() { _ = server.Shutdown() }, nil +} + +// LANAddresses lists the up, multicast-capable, physical interfaces' IPv4 +// addresses. VPN, tunnel, container and loopback interfaces are skipped: a LAN +// client cannot dial them (the tailnet address is reached by name instead). +func LANAddresses() []net.IP { + interfaces, err := net.Interfaces() + if err != nil { + return nil + } + var ips []net.IP + for _, iface := range interfaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagMulticast == 0 || iface.Flags&net.FlagLoopback != 0 || virtual(iface.Name) { + continue + } + addrs, err := iface.Addrs() + if err != nil { + continue + } + for _, addr := range addrs { + network, ok := addr.(*net.IPNet) + if !ok { + continue + } + if ip4 := network.IP.To4(); ip4 != nil && !ip4.IsLinkLocalUnicast() && !ip4.IsLoopback() { + ips = append(ips, ip4) + } + } + } + return ips +} + +func virtual(name string) bool { + for _, prefix := range []string{"lo", "docker", "veth", "br-", "virbr", "tun", "tap", "utun", "wg", "tailscale", "zt", "vpn", "bridge", "awdl", "llw", "anpi", "ap"} { + if strings.HasPrefix(name, prefix) { + return true + } + } + return false +} diff --git a/internal/discovery/advertise_test.go b/internal/discovery/advertise_test.go new file mode 100644 index 00000000..8b454189 --- /dev/null +++ b/internal/discovery/advertise_test.go @@ -0,0 +1,122 @@ +package discovery + +import ( + "errors" + "net" + "slices" + "testing" + + "github.com/miekg/dns" +) + +var lan = []net.IP{net.ParseIP("192.168.1.20").To4()} + +func TestPlanAdvertisesTheWebProxyWithPasswordAuth(t *testing.T) { + advert, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Version: "v1.4.0", Hostname: "Alans-Mac.local", IPs: lan}) + if err != nil { + t.Fatal(err) + } + if advert.Port != 8083 || advert.Instance != "Pipelines-Alans-Mac" || advert.Host != "Alans-Mac.local." { + t.Fatalf("advert = %+v", advert) + } + want := []string{"v=v1.4.0", "name=Alans-Mac", "path=/connect", "tls=0", "auth=password"} + if !slices.Equal(advert.TXT, want) { + t.Fatalf("TXT = %q, want %q", advert.TXT, want) + } +} + +func TestPlanAdvertisesADirectLANListenerWithoutAuth(t *testing.T) { + advert, err := Plan(Config{ListenAddr: "0.0.0.0:8080", Hostname: "box", IPs: lan}) + if err != nil { + t.Fatal(err) + } + if advert.Port != 8080 || !slices.Contains(advert.TXT, "auth=none") || !slices.Contains(advert.TXT, "v=dev") { + t.Fatalf("advert = %+v", advert) + } +} + +func TestPlanRefusesWhatALANClientCannotDial(t *testing.T) { + for name, cfg := range map[string]Config{ + "loopback only": {ListenAddr: "127.0.0.1:8080", Hostname: "box", IPs: lan}, + "localhost only": {ListenAddr: "localhost:8080", Hostname: "box", IPs: lan}, + "no LAN address": {ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Hostname: "box"}, + } { + if _, err := Plan(cfg); !errors.Is(err, ErrNotReachable) { + t.Errorf("%s: err = %v, want ErrNotReachable", name, err) + } + } + if _, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 70000, IPs: lan}); err == nil { + t.Error("out-of-range port accepted") + } +} + +func TestHostLabelIsOneSafeDNSLabel(t *testing.T) { + for in, want := range map[string]string{ + "Alans-MacBook-Pro.local": "Alans-MacBook-Pro", + "my box_2": "my-box-2", + "": "pipelines", + "...": "pipelines", + } { + if got := hostLabel(in); got != want { + t.Errorf("hostLabel(%q) = %q, want %q", in, got, want) + } + } +} + +// The zone answers a DNS-SD browse (PTR), resolve (SRV + TXT) and address +// lookup (A) with the advertised content. +func TestZoneAnswersBrowseResolveAndAddressQueries(t *testing.T) { + advert, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Version: "v2", Hostname: "box", IPs: lan}) + if err != nil { + t.Fatal(err) + } + zone, err := advert.Zone() + if err != nil { + t.Fatal(err) + } + instance := "Pipelines-box._pipelines._tcp.local." + + ptr := zone.Records(dns.Question{Name: "_pipelines._tcp.local.", Qtype: dns.TypePTR, Qclass: dns.ClassINET}) + if len(ptr) == 0 || ptr[0].(*dns.PTR).Ptr != instance { + t.Fatalf("PTR = %v", ptr) + } + srv := zone.Records(dns.Question{Name: instance, Qtype: dns.TypeSRV, Qclass: dns.ClassINET}) + if len(srv) == 0 || srv[0].(*dns.SRV).Port != 8083 || srv[0].(*dns.SRV).Target != "box.local." { + t.Fatalf("SRV = %v", srv) + } + txt := zone.Records(dns.Question{Name: instance, Qtype: dns.TypeTXT, Qclass: dns.ClassINET}) + if len(txt) != 1 || !slices.Equal(txt[0].(*dns.TXT).Txt, advert.TXT) { + t.Fatalf("TXT = %v", txt) + } + a := zone.Records(dns.Question{Name: "box.local.", Qtype: dns.TypeA, Qclass: dns.ClassINET}) + if len(a) != 1 || !a[0].(*dns.A).A.Equal(lan[0]) { + t.Fatalf("A = %v", a) + } + // The records survive a wire round trip unescaped. + msg := new(dns.Msg) + msg.Answer = append(append(ptr, srv...), txt...) + packed, err := msg.Pack() + if err != nil { + t.Fatal(err) + } + var back dns.Msg + if err := back.Unpack(packed); err != nil { + t.Fatal(err) + } + if back.Answer[0].(*dns.PTR).Ptr != instance { + t.Fatalf("round trip PTR = %v", back.Answer[0]) + } +} + +func TestVirtualInterfacesAreSkipped(t *testing.T) { + for _, name := range []string{"utun3", "tailscale0", "docker0", "lo0", "awdl0", "bridge100"} { + if !virtual(name) { + t.Errorf("%s treated as LAN", name) + } + } + for _, name := range []string{"en0", "eth0", "wlan0", "enp3s0"} { + if virtual(name) { + t.Errorf("%s treated as virtual", name) + } + } +} diff --git a/scripts/manage.py b/scripts/manage.py index e32389d8..9f958559 100644 --- a/scripts/manage.py +++ b/scripts/manage.py @@ -38,6 +38,18 @@ def server_address(config): return f"{config.get('bind_address') or '127.0.0.1'}:{config['server_port']}" +def mdns_args(config): + """The LAN port the server advertises over mDNS. + + LAN clients dial the authenticated web proxy, not the loopback server, so + the proxy's port is advertised when the proxy listens beyond loopback. + """ + web = config.get("web") or {} + if web.get("port") and web.get("host") not in (None, "", "127.0.0.1", "localhost", "::1"): + return ["-mdns-port", str(web["port"])] + return [] + + def load(prefix): prefix = Path(prefix).expanduser().resolve() path = prefix / MARKER @@ -408,6 +420,7 @@ def supervise(config): server_address(config), "-db", str(root / "data/pipelines.db")] if config.get("allow_authoring") is True: server_command.append("-allow-authoring") + server_command += mdns_args(config) with (root / "logs/server.log").open("a") as log: child = subprocess.Popen(server_command, cwd=config["workspace"], env=env, stdout=log, stderr=log) if config.get("web"): diff --git a/scripts/test_manage_native.py b/scripts/test_manage_native.py index 650a2a8c..4ab25f72 100644 --- a/scripts/test_manage_native.py +++ b/scripts/test_manage_native.py @@ -144,6 +144,15 @@ class ManageNativeTests(unittest.TestCase): "-db", str(root / "data/pipelines.db")]) self.assertEqual("-allow-authoring" in command, role is True) + def test_mdns_advertises_the_lan_web_proxy_port(self): + with tempfile.TemporaryDirectory() as directory: + config = self.config(Path(directory)) + self.assertEqual(manage.mdns_args(config), []) + config["web"]["host"] = "0.0.0.0" + self.assertEqual(manage.mdns_args(config), ["-mdns-port", "8082"]) + config.pop("web") + self.assertEqual(manage.mdns_args(config), []) + def config(self, root, mode="native"): (root / "lib/app-web").mkdir(parents=True, exist_ok=True) (root / "lib/app-web/index.html").write_text("app")