Find LAN servers from browser and review discovered machine names

This commit is contained in:
2026-11-08 21:50:27 +00:00
parent 543e3f063a
commit b69d7efb4a
12 changed files with 371 additions and 12 deletions
@@ -0,0 +1,3 @@
Future<String> fetchDiscovery() => Future.error(
UnsupportedError('Browser discovery requires the web client.'),
);
@@ -0,0 +1,30 @@
import 'dart:js_interop';
@JS('fetch')
external JSPromise<_Response> _fetch(JSString url, _Options options);
extension type _Options._(JSObject _) implements JSObject {
external factory _Options({JSString credentials, JSString cache});
}
extension type _Response._(JSObject _) implements JSObject {
external int get status;
external JSPromise<JSString> text();
}
Future<String> fetchDiscovery() async {
final response = await _fetch(
'/api/discovery'.toJS,
_Options(credentials: 'same-origin'.toJS, cache: 'no-store'.toJS),
).toDart;
if (response.status == 401 || response.status == 403) {
throw StateError('Sign in to this server before searching the network.');
}
if (response.status == 404) {
throw StateError('Update this server to enable browser network discovery.');
}
if (response.status != 200) {
throw StateError('Network discovery failed (HTTP ${response.status}).');
}
return (await response.text().toDart).toDart;
}
@@ -0,0 +1,59 @@
import 'dart:convert';
import '../../../core/transport/server_url.dart';
import 'discovered_server.dart';
import 'server_discovery.dart';
import 'browser_discovery_fetch_stub.dart'
if (dart.library.js_interop) 'browser_discovery_fetch_web.dart'
as impl;
/// The authenticated web front door browses its LAN on the browser's behalf.
class BrowserServerDiscovery implements ServerDiscovery {
BrowserServerDiscovery({Future<String> Function()? fetch})
: _fetch = fetch ?? impl.fetchDiscovery;
final Future<String> Function() _fetch;
@override
Stream<List<DiscoveredServer>> scan() async* {
final body = await _fetch().timeout(const Duration(seconds: 8));
if (body.length > 262144) {
throw const FormatException('Discovery response is too large.');
}
final envelope = jsonDecode(body);
if (envelope is! Map || envelope['discovered_servers'] is! List) {
throw const FormatException(
'This server did not return network discovery results.',
);
}
final servers = <Uri, DiscoveredServer>{};
for (final item in (envelope['discovered_servers'] as List).take(256)) {
if (item is! Map ||
item['endpoint'] is! String ||
item['name'] is! String) {
continue;
}
try {
final validated = ServerUrl.validate(item['endpoint'] as String);
final uri = Uri.parse(validated.wsUrl);
final name = (item['name'] as String).trim();
if (name.isEmpty ||
name.length > 256 ||
uri.hasQuery ||
uri.hasFragment) {
continue;
}
servers[uri] = DiscoveredServer(
name: name,
host: uri.host,
port: validated.port,
secure: uri.scheme == 'wss',
path: uri.path,
passwordRequired: item['auth'] != 'none',
version: item['version'] is String ? item['version'] as String : null,
);
} on FormatException {
// One malformed announcement must not hide other machines.
}
}
yield servers.values.toList();
}
}
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import 'discovered_server.dart';
import 'browser_server_discovery.dart';
import 'server_discovery.dart';
enum _Phase { idle, scanning, done, failed }
@@ -62,6 +63,12 @@ class _DiscoveryPanelState extends State<DiscoveryPanel> {
(servers) {
if (mounted) setState(() => _servers = servers);
},
onDone: () {
_timer?.cancel();
if (mounted && _phase == _Phase.scanning) {
setState(() => _phase = _Phase.done);
}
},
onError: (Object error) {
_stop();
if (mounted) {
@@ -126,6 +133,8 @@ class _DiscoveryPanelState extends State<DiscoveryPanel> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
button,
if (widget.discovery is BrowserServerDiscovery)
const Text('Searches this server’s local network.'),
?status,
for (final server in _servers) _row(context, cupertino, server),
],
@@ -1,6 +1,7 @@
import 'package:flutter/foundation.dart';
import 'bonsoir_server_discovery.dart';
import 'browser_server_discovery.dart';
import 'discovered_server.dart';
/// Finds Pipelines servers on the local network.
@@ -12,7 +13,7 @@ abstract interface class ServerDiscovery {
/// 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.
/// Browsers ask their authenticated front door to browse its LAN. Native
/// clients browse directly through the platform DNS-SD service.
ServerDiscovery? platformServerDiscovery({bool web = kIsWeb}) =>
web ? null : BonsoirServerDiscovery();
web ? BrowserServerDiscovery() : BonsoirServerDiscovery();
@@ -26,6 +26,7 @@ class OnboardingFlow extends StatefulWidget {
this.check = ServerSession.check,
this.signIn = ServerSession.signIn,
this.saveServer,
this.saveServerProfile,
this.savedServers,
this.serverAddresses = const [],
this.discovery,
@@ -42,10 +43,11 @@ class OnboardingFlow extends StatefulWidget {
final ServerCheck check;
final ServerSignIn signIn;
final Future<void> Function(String url)? saveServer;
final Future<void> Function(String url, String name)? saveServerProfile;
final Widget? savedServers;
final List<Uri> serverAddresses;
/// LAN discovery; null hides the scan (web, or no platform support).
/// Network discovery; null hides the scan when no service was supplied.
final ServerDiscovery? discovery;
@override
@@ -57,6 +59,7 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
text: widget.initialServer,
);
final TextEditingController _password = TextEditingController();
final TextEditingController _name = TextEditingController();
late bool _passwordStep = widget.startAtPassword;
Uri? _endpoint;
bool _busy = false;
@@ -72,6 +75,7 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
void dispose() {
_server.dispose();
_password.dispose();
_name.dispose();
super.dispose();
}
@@ -120,7 +124,14 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
return;
}
try {
await widget.saveServer?.call(endpoint.toString());
if (widget.saveServerProfile != null) {
await widget.saveServerProfile!(
endpoint.toString(),
_name.text.trim().isEmpty ? endpoint.host : _name.text.trim(),
);
} else {
await widget.saveServer?.call(endpoint.toString());
}
} catch (error) {
if (mounted) {
setState(() {
@@ -143,8 +154,11 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
}
void _useDiscovered(DiscoveredServer server) {
_server.text = server.endpoint.toString();
_continue();
setState(() {
_server.text = server.endpoint.toString();
_name.text = server.name;
_error = null;
});
}
Future<void> _signIn() async {
@@ -241,6 +255,16 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
Text(lead),
const SizedBox(height: 24),
field,
if (!_passwordStep) ...[
const SizedBox(height: 12),
_field(
cupertino,
key: const Key('onboarding-server-name'),
controller: _name,
hint: 'Machine name',
onSubmitted: _continue,
),
],
if (_error != null) ...[
const SizedBox(height: 8),
Text(
@@ -4,15 +4,23 @@ import 'package:flutter/material.dart';
import '../../ui/adaptive/segmented_bar.dart';
import '../../core/servers/server_catalog.dart';
import '../../ui/adaptive/host.dart';
import '../onboarding/discovery/discovered_server.dart';
import '../onboarding/discovery/discovery_panel.dart';
import '../onboarding/discovery/server_discovery.dart';
/// When supplied, [onSave] must finish successfully before the route closes.
/// Throwing keeps the draft open and displays the error for a retry.
Future<SavedServer?> editSavedServer(
BuildContext context, {
SavedServer? server,
ServerDiscovery? discovery,
Future<void> Function(SavedServer)? onSave,
}) {
final page = _ServerEditor(server: server, onSave: onSave);
final page = _ServerEditor(
server: server,
onSave: onSave,
discovery: discovery ?? platformServerDiscovery(),
);
return Navigator.of(context).push<SavedServer>(
usesCupertinoHost(context)
? CupertinoPageRoute(builder: (_) => page)
@@ -21,7 +29,8 @@ Future<SavedServer?> editSavedServer(
}
class _ServerEditor extends StatefulWidget {
const _ServerEditor({this.server, this.onSave});
const _ServerEditor({this.server, this.onSave, this.discovery});
final ServerDiscovery? discovery;
final SavedServer? server;
final Future<void> Function(SavedServer)? onSave;
@@ -41,6 +50,14 @@ class _ServerEditorState extends State<_ServerEditor> {
String? _error;
bool _saving = false;
void _useDiscovered(DiscoveredServer server) {
setState(() {
_name.text = server.name;
_addresses.text = server.endpoint.toString();
_error = null;
});
}
Future<void> _save() async {
if (_saving) return;
try {
@@ -136,6 +153,14 @@ class _ServerEditorState extends State<_ServerEditor> {
child: ListView(
padding: const EdgeInsets.all(16),
children: [
if (widget.server == null && widget.discovery != null) ...[
DiscoveryPanel(
discovery: widget.discovery!,
enabled: !_saving,
onSelect: _useDiscovered,
),
const SizedBox(height: 16),
],
_field(_name, 'Server name', key: 'server-profile-name'),
const SizedBox(height: 16),
_field(