60 lines
2.0 KiB
Dart
60 lines
2.0 KiB
Dart
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();
|
|
}
|
|
}
|