Files
alan 9f38e38f6a Sign the app update feed with Ed25519 and verify it in the app
Each installation generates a private Ed25519 key once (0600, under
~/.config/pipelines), signs version.json with a detached version.json.sig
when publishing APK and desktop builds, and embeds its own and listed
trusted public keys in app builds. The app verifies the feed signature
before trusting the artifact sha256, refuses unsigned or foreign feeds when
it has keys, and requires the sha256 and Android signer in signed feeds.
2026-11-10 00:51:16 +00:00

236 lines
7.6 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].
///
/// A [signed] feed (its signature verified with a key the build trusts)
/// must name the artifact's sha256 and, for Android, its signing
/// certificate: an unsigned build tolerates their absence, a signed one
/// does not.
static AppUpdate? parse(
String body,
Uri base, {
String platform = 'android',
String architecture = 'arm64',
String? installedSignature,
bool signed = false,
}) {
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 (signed && digest.isEmpty) return null;
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 (signed &&
platform == 'android' &&
(signer is! String || installedSignature == null)) {
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),
),
);