Files
pipelines/app/lib/features/updates/app_updates.dart
T

224 lines
7.1 KiB
Dart

import 'dart:convert';
import '../../core/servers/server_catalog.dart';
import '../../core/session/server_session.dart';
import 'app_updates_stub.dart'
if (dart.library.io) 'app_updates_io.dart'
as impl;
/// The latest app build the server offers, from its `updates/version.json`.
class AppUpdate {
const AppUpdate({
required this.versionCode,
required this.versionName,
required this.apk,
this.notes = '',
this.sourceName = '',
this.headersFor,
this.platform = 'android',
this.sha256 = '',
this.signingCertificateSha256 = '',
});
final int versionCode;
final String versionName;
final Uri apk;
final String notes;
final String sourceName;
final String platform;
final String sha256;
final String signingCertificateSha256;
final Map<String, String> Function(Uri)? headersFor;
AppUpdate fromServer(
String name,
Map<String, String> Function(Uri) headers,
) => AppUpdate(
versionCode: versionCode,
versionName: versionName,
apk: apk,
notes: notes,
platform: platform,
sourceName: name,
sha256: sha256,
signingCertificateSha256: signingCertificateSha256,
headersFor: headers,
);
/// Reads `version.json`; the APK path is relative to [base].
static AppUpdate? parse(
String body,
Uri base, {
String platform = 'android',
String architecture = 'arm64',
String? installedSignature,
}) {
try {
final json = jsonDecode(body);
if (json is! Map) return null;
final code = json['versionCode'];
final file = '${json[platform == 'android' ? 'apk' : 'file'] ?? ''}'
.trim();
if (code is! int ||
code < 1 ||
file.isEmpty ||
!RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._-]*$').hasMatch(file)) {
return null;
}
final digest = '${json['sha256'] ?? ''}';
if (digest.isNotEmpty && !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(digest)) {
return null;
}
final signer = json['signingCertificateSha256'];
if (signer != null &&
(signer is! String ||
!RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(signer))) {
return null;
}
if (platform == 'android' &&
signer is String &&
installedSignature != null &&
signer.toLowerCase() !=
installedSignature.replaceAll(':', '').trim().toLowerCase()) {
return null;
}
if (platform == 'android' &&
json['platform'] != null &&
json['platform'] != 'android') {
return null;
}
if (platform != 'android' &&
(json['platform'] != platform ||
json['architectures'] is! List ||
!(json['architectures'] as List).contains(architecture))) {
return null;
}
return AppUpdate(
versionCode: code,
platform: platform,
sha256: '${json['sha256'] ?? ''}',
signingCertificateSha256: signer is String ? signer.toLowerCase() : '',
versionName: '${json['versionName'] ?? ''}',
apk: base.resolve(file),
notes: '${json['notes'] ?? ''}',
);
} on FormatException {
return null;
}
}
}
/// Where a build set its update feed (`--dart-define=PIPELINES_UPDATES_URL`),
/// blank for the default.
const configuredUpdatesUrl = String.fromEnvironment('PIPELINES_UPDATES_URL');
/// The update feed for [endpoint]: `/updates/` on the server's own web origin
/// (the installed web proxy serves the APK there), or [configured] when the
/// build named another feed.
Uri? updatesBaseFor(Uri endpoint, {String configured = configuredUpdatesUrl}) {
final override = configured.trim();
if (override.isNotEmpty) {
final parsed = Uri.tryParse(override);
if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) {
return parsed.path.endsWith('/')
? parsed
: parsed.replace(path: '${parsed.path}/');
}
}
if (endpoint.host.isEmpty) return null;
final secure = endpoint.scheme == 'wss' || endpoint.scheme == 'https';
return Uri(
scheme: secure ? 'https' : 'http',
host: endpoint.host,
port: endpoint.hasPort ? endpoint.port : null,
path: '/updates/',
);
}
/// Whether this native build supports platform-compatible update downloads.
bool get appUpdatesSupported => impl.supported;
/// The installed build number, or null where there is none to compare.
Future<int?> installedVersionCode() => impl.installedVersionCode();
/// Fetches the latest offered build, or throws what went wrong in words.
Future<AppUpdate> fetchLatestUpdate(Uri base) => impl.fetchLatest(base);
/// Downloads [update] (reporting 0..1 progress) and hands it to the system
/// installer.
Future<void> downloadAndInstall(
AppUpdate update, {
void Function(double progress)? onProgress,
}) => impl.downloadAndInstall(update, onProgress: onProgress);
/// Checks each logical machine independently; aliases share only its credential.
/// Failed machines cannot hide a newer compatible build on a healthy machine.
Future<AppUpdate> newestServerUpdate(
Iterable<SavedServer> servers, {
Future<AppUpdate> Function(Uri, Map<String, String> Function(Uri))? read,
bool Function(SavedServer server, Uri uri)? stillTrusted,
}) async {
final results = await Future.wait(
servers.map((server) async {
Map<String, String> Function(Uri) headers;
try {
headers = await ServerSession.credentialReader(
id: server.id,
endpoints: server.endpoints.map(Uri.parse),
);
} catch (_) {
return null;
}
final snapshotHeaders = headers;
headers = (uri) {
if (stillTrusted != null && !stillTrusted(server, uri)) {
throw StateError(
'The update server is no longer a saved trusted address.',
);
}
return snapshotHeaders(uri);
};
final candidates = await Future.wait(
server.endpoints.map((endpoint) async {
final base = updatesBaseFor(Uri.parse(endpoint), configured: '');
if (base == null) return null;
try {
final update = await (read ?? impl.fetchLatestScoped)(
base,
headers,
).timeout(const Duration(seconds: 15));
return update.fromServer(server.name, headers);
} catch (_) {
return null;
}
}),
);
final builds = candidates.whereType<AppUpdate>().toList()
..sort((a, b) => b.versionCode.compareTo(a.versionCode));
return builds.isEmpty ? null : builds.first;
}),
);
final available = results.whereType<AppUpdate>().toList()
..sort((a, b) => b.versionCode.compareTo(a.versionCode));
if (available.isEmpty) {
throw const FormatException(
'No compatible update could be read. Check your saved servers and sign-ins.',
);
}
return available.first;
}
/// Retained offers must stop trusting an alias if its profile is edited/removed.
bool updateSourceStillTrusted(
Iterable<SavedServer> current,
SavedServer source,
Uri uri,
) => current.any(
(server) =>
server.id == source.id &&
server.endpoints.any(
(endpoint) => loginUriFor(Uri.parse(endpoint)) == loginUriFor(uri),
),
);