One Flutter client for network-computer: drive a remote Linux/Mac desktop from Android, iPhone, iPad, or desktop over WebRTC.

0 downloads

network-computer-flutter/lib/signaling.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/network-computer-flutter.git
HTTPS
https://gitstable.com/git/askrobots/network-computer-flutter.git
SSH
ssh://git@gitstable.com:2222/askrobots/network-computer-flutter.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Quellhorst No colour (compare) in ⋯: the desk's picture in grey on this device c74471a 1 month, 3 weeks ago History
signaling.dart · 4.6 KB · 126 lines
1import 'dart:async';
2import 'dart:convert';
3import 'dart:io';
4import 'package:crypto/crypto.dart';
5import 'protocol.dart';
6
7/// Endpoint + Basic auth for the rendezvous.
8class Endpoint {
9 final Uri base; // http(s)://host:port
10 final String user, password;
11
12 /// SHA-256 of the rendezvous certificate, for a self-signed secure-mode
13 /// server. Empty means normal certificate-authority verification.
14 final String fingerprint;
15 Endpoint(this.base, this.user, this.password, {String fingerprint = ''})
16 : fingerprint = normalizeFingerprint(fingerprint);
17
18 String get authHeader =>
19 'Basic ${base64.encode(utf8.encode('$user:$password'))}';
20
21 Uri get wsUri {
22 final scheme = base.scheme == 'https' ? 'wss' : 'ws';
23 return base.replace(scheme: scheme, path: '/ws');
24 }
25}
26
27/// Accepts "AB:CD:..", "abcd..", or "sha256 abcd.."; returns lowercase hex.
28String normalizeFingerprint(String fp) {
29 var f = fp.trim().toLowerCase();
30 if (f.startsWith('sha256')) f = f.substring(6);
31 return f.replaceAll(RegExp(r'[^0-9a-f]'), '');
32}
33
34/// An HttpClient for [ep]. With a fingerprint it trusts no certificate
35/// authority at all and accepts exactly the one certificate whose SHA-256
36/// matches, so a CA-issued cert from an attacker is refused too.
37HttpClient clientFor(Endpoint ep) {
38 if (ep.fingerprint.isEmpty) return HttpClient();
39 final c = HttpClient(context: SecurityContext(withTrustedRoots: false));
40 c.badCertificateCallback = (X509Certificate cert, String host, int port) =>
41 sha256.convert(cert.der).toString() == ep.fingerprint;
42 return c;
43}
44
45/// WebSocket signaling + the /config and /hosts HTTP calls.
46///
47/// Credentials are exchanged once at POST /auth for a bearer token, which is
48/// then used for every call. The rendezvous also still accepts HTTP Basic, so
49/// this degrades gracefully against an older server.
50class SignalingClient {
51 final Endpoint ep;
52 WebSocket? _ws;
53 String? _token;
54 String mode = 'insecure';
55 void Function(SignalMessage)? onMessage;
56 void Function(Object?)? onClose;
57
58 SignalingClient(this.ep) : _http = clientFor(ep);
59
60 final HttpClient _http;
61
62 /// Trade username+password for a token. Falls back to Basic if the server
63 /// has no /auth endpoint.
64 Future<void> authenticate() async {
65 try {
66 final req = await _http.postUrl(ep.base.replace(path: '/auth'));
67 req.headers.contentType = ContentType.json;
68 req.write(jsonEncode({'user': ep.user, 'password': ep.password}));
69 final resp = await req.close();
70 final body = await resp.transform(utf8.decoder).join();
71 if (resp.statusCode == 401) throw 'Rendezvous rejected the password';
72 if (resp.statusCode == 404) return; // older server: stay on Basic
73 if (resp.statusCode >= 300) throw 'Rendezvous returned HTTP ${resp.statusCode}';
74 final j = jsonDecode(body) as Map<String, dynamic>;
75 _token = j['token'] as String?;
76 mode = (j['mode'] as String?) ?? 'insecure';
77 } on HandshakeException {
78 throw ep.fingerprint.isEmpty
79 ? 'TLS certificate not trusted (self-signed? add its fingerprint)'
80 : 'TLS fingerprint does not match this rendezvous';
81 } on SocketException catch (e) {
82 throw 'Cannot reach rendezvous: ${e.message}';
83 }
84 }
85
86 String get _authHeader =>
87 _token != null ? 'Bearer $_token' : ep.authHeader;
88
89 Future<T> _getJson<T>(String path, T Function(dynamic) parse) async {
90 final req = await _http.getUrl(ep.base.replace(path: path));
91 req.headers.set(HttpHeaders.authorizationHeader, _authHeader);
92 final resp = await req.close();
93 if (resp.statusCode == 401) throw 'Rendezvous rejected the password';
94 if (resp.statusCode >= 300) throw 'Rendezvous returned HTTP ${resp.statusCode}';
95 final body = await resp.transform(utf8.decoder).join();
96 return parse(jsonDecode(body));
97 }
98
99 Future<List<IceServer>> fetchIceServers() => _getJson('/config', (j) =>
100 ((j['iceServers'] as List?) ?? [])
101 .map((e) => IceServer.fromJson((e as Map).cast<String, dynamic>()))
102 .toList());
103
104 Future<List<String>> fetchHosts() =>
105 _getJson('/hosts', (j) => (j as List).cast<String>());
106
107 Future<void> connect() async {
108 final ws = await WebSocket.connect(ep.wsUri.toString(),
109 headers: {HttpHeaders.authorizationHeader: _authHeader},
110 customClient: _http);
111 _ws = ws;
112 ws.listen(
113 (data) {
114 try {
115 onMessage?.call(SignalMessage.fromJson(jsonDecode(data as String)));
116 } catch (_) {}
117 },
118 onDone: () => onClose?.call(null),
119 onError: (e) => onClose?.call(e),
120 cancelOnError: true,
121 );
122 }
123
124 void send(SignalMessage m) => _ws?.add(jsonEncode(m.toJson()));
125 void close() => _ws?.close();
126}