Files

113 lines
3.6 KiB
Dart
Raw Permalink Normal View History

// The server as reached through the private relay: every request and socket
// rides the E2EE tunnel started from the pairing link's relay candidate.
import 'dart:async';
import 'dart:convert';
import '../l10n.dart';
import '../version.dart';
import 'relay_tunnel.dart';
import 'transport.dart';
class RelayTransport implements Transport {
final RelayTunnel _tunnel;
String? _bearer;
String? _urlToken;
DateTime _urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
Future<String>? _minting;
RelayTransport({
required String relayUrl,
required String serverId,
required Map<String, dynamic> hostKey,
String? grant,
String? version,
}) : _tunnel = RelayTunnel(
relayUrl: relayUrl,
serverId: serverId,
hostKey: hostKey,
grant: grant,
// Read at construction: the version is known once the app has
// started, which is after this default would have been fixed.
appVersion: version ?? appVersion,
);
@override
Future<TransportResponse> send(TransportRequest request) =>
_tunnel.send(request);
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async {
final token = await _mintUrlToken();
final query = [
if (rawQuery != null && rawQuery.isNotEmpty) rawQuery,
if (token.isNotEmpty) 'oc_url_token=${Uri.encodeQueryComponent(token)}',
].join('&');
return _tunnel.openWebSocket(path, rawQuery: query, headers: headers);
}
@override
void setBearerToken(String? token) {
if (_bearer != token) {
_bearer = token;
_urlToken = null;
_urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
}
}
/// WebSocket upgrades cannot carry headers, so the host expects a short-lived
/// URL-scoped token minted over the same tunnel with the bearer.
Future<String> _mintUrlToken() async {
final bearer = _bearer;
if (bearer == null || bearer.isEmpty) return '';
if (_urlToken != null && _urlToken!.isNotEmpty &&
DateTime.now().isBefore(_urlTokenExpiresAt)) {
return _urlToken!;
}
final inFlight = _minting;
if (inFlight != null) return inFlight;
final future = _mint(bearer);
_minting = future;
try {
return await future;
} finally {
_minting = null;
}
}
Future<String> _mint(String bearer) async {
final response = await _tunnel.send(TransportRequest(
method: 'POST',
path: '/auth/url-token',
headers: {'authorization': 'Bearer $bearer', 'accept': 'application/json'},
));
final bytes = await response.body
.fold<List<int>>(<int>[], (all, chunk) => all..addAll(chunk));
if (response.status < 200 || response.status >= 300) {
throw RelayTunnelException(trArgs('Could not get a WebSocket token ({0})', [response.status]));
}
try {
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
if (decoded is! Map) return '';
final token = decoded['token'];
if (token is! String) return '';
final expiresIn = decoded['expiresIn'];
final expiresAt = decoded['expiresAt'];
final lifetime = expiresIn is num
? Duration(seconds: expiresIn.toInt())
: expiresAt is num && expiresAt > 0
? Duration(milliseconds: expiresAt.toInt())
: const Duration(minutes: 4);
_urlToken = token.trim();
_urlTokenExpiresAt = DateTime.now()
.add(lifetime)
.subtract(const Duration(seconds: 20));
return _urlToken!;
} catch (_) {
return '';
}
}
@override
void close() => _tunnel.close();
}