Merge branch 'worktree-agent-a5eba3669bc0e09ad' into worktree-agent-ac54c8919e940163a

This commit is contained in:
2026-11-10 01:02:08 +00:00
17 changed files with 1010 additions and 26 deletions
+12
View File
@@ -47,12 +47,18 @@ class AppUpdate {
);
/// 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);
@@ -67,6 +73,7 @@ class AppUpdate {
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;
}
@@ -76,6 +83,11 @@ class AppUpdate {
!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 &&
+45 -11
View File
@@ -11,6 +11,7 @@ import 'package:path_provider/path_provider.dart';
import '../../core/session/server_session.dart';
import 'app_updates.dart';
import 'linux_self_update.dart';
import 'update_feed_signature.dart';
bool get supported =>
Platform.isAndroid || Platform.isLinux || Platform.isMacOS;
@@ -57,10 +58,42 @@ Future<HttpClientResponse> _get(
Future<AppUpdate> fetchLatest(Uri base) =>
fetchLatestScoped(base, ServerSession.headersFor);
Future<AppUpdate> fetchLatestScoped(
Uri base,
/// Reads at most [limit] bytes of [response].
Future<List<int>> _body(HttpClientResponse response, int limit) async {
final chunks = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
if (chunks.length + chunk.length > limit) {
throw const FormatException('Update metadata is too large.');
}
chunks.addAll(chunk);
}
return chunks;
}
/// The detached feed signature, or null when the server offers none.
Future<String?> _signature(
HttpClient client,
Uri feed,
Map<String, String> Function(Uri) headers,
) async {
try {
final response = await _get(
client,
feed.resolve('version.json.sig'),
headers,
);
return utf8.decode(await _body(response, 4096));
} on HttpException {
return null;
}
}
Future<AppUpdate> fetchLatestScoped(
Uri base,
Map<String, String> Function(Uri) headers, {
List<List<int>>? trustedKeys,
}) async {
final trusted = trustedKeys ?? trustedUpdateKeys();
final platform = nativePlatform;
if (platform == 'linux' && nativeArchitecture != 'x64') {
throw const FormatException(
@@ -73,15 +106,15 @@ Future<AppUpdate> fetchLatestScoped(
final client = HttpClient()..connectionTimeout = const Duration(seconds: 10);
try {
final response = await _get(client, feed.resolve('version.json'), headers);
var bytes = 0;
final chunks = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 10))) {
bytes += chunk.length;
if (bytes > 65536) {
throw const FormatException('Update metadata is too large.');
}
chunks.addAll(chunk);
}
final chunks = await _body(response, 65536);
// The signature is checked before anything in the feed (the artifact's
// sha256 above all) is believed.
final problem = feedSignatureProblem(
chunks,
trusted.isEmpty ? null : await _signature(client, feed, headers),
trusted,
);
if (problem != null) throw FormatException(problem);
final update = AppUpdate.parse(
utf8.decode(chunks),
feed,
@@ -90,6 +123,7 @@ Future<AppUpdate> fetchLatestScoped(
installedSignature: platform == 'android'
? (await PackageInfo.fromPlatform()).buildSignature
: null,
signed: trusted.isNotEmpty,
);
if (update == null) {
throw const FormatException('No compatible build is offered.');
+140
View File
@@ -0,0 +1,140 @@
import 'dart:typed_data';
import 'package:crypto/crypto.dart' as crypto;
/// Ed25519 signature verification (RFC 8032 section 5.1.7), verify only.
///
/// The update feed is checked once per update, so plain [BigInt] arithmetic
/// is fast enough and keeps this small and auditable; it never handles a
/// private key, so constant-time arithmetic is not required. Tested against
/// the RFC 8032 vectors in `test/features/updates/ed25519_test.dart`.
bool ed25519Verify({
required List<int> publicKey,
required List<int> message,
required List<int> signature,
}) {
if (publicKey.length != 32 || signature.length != 64) return false;
final a = _decode(publicKey);
final r = _decode(signature.sublist(0, 32));
if (a == null || r == null) return false;
final s = _littleEndian(signature.sublist(32));
if (s >= _l) return false;
final digest = crypto.sha512.convert([
...signature.sublist(0, 32),
...publicKey,
...message,
]);
final k = _littleEndian(digest.bytes) % _l;
final left = _multiply(_base, s);
final right = _add(r, _multiply(a, k));
return _equal(_encode(left), _encode(right));
}
final BigInt _p = (BigInt.one << 255) - BigInt.from(19);
final BigInt _l =
(BigInt.one << 252) +
BigInt.parse('27742317777372353535851937790883648493');
final BigInt _d =
(BigInt.from(-121665) * BigInt.from(121666).modInverse(_p)) % _p;
final BigInt _sqrtMinusOne = BigInt.two.modPow((_p - BigInt.one) >> 2, _p);
final _Point _base = _decode(_baseEncoding)!;
// The base point: y = 4/5, x even.
final List<int> _baseEncoding = _bytes(
(BigInt.from(4) * BigInt.from(5).modInverse(_p)) % _p,
);
/// Extended coordinates (X:Y:Z:T) with x = X/Z, y = Y/Z, x*y = T/Z.
class _Point {
const _Point(this.x, this.y, this.z, this.t);
final BigInt x, y, z, t;
}
final _Point _identity = _Point(
BigInt.zero,
BigInt.one,
BigInt.one,
BigInt.zero,
);
BigInt _littleEndian(List<int> bytes) {
var value = BigInt.zero;
for (var i = bytes.length - 1; i >= 0; i--) {
value = (value << 8) | BigInt.from(bytes[i]);
}
return value;
}
List<int> _bytes(BigInt value) {
final out = Uint8List(32);
var rest = value;
for (var i = 0; i < 32; i++) {
out[i] = (rest & BigInt.from(0xff)).toInt();
rest >>= 8;
}
return out;
}
_Point? _decode(List<int> encoded) {
final bytes = List<int>.of(encoded);
final sign = bytes[31] >> 7;
bytes[31] &= 0x7f;
final y = _littleEndian(bytes);
if (y >= _p) return null;
final y2 = y * y % _p;
final u = (y2 - BigInt.one) % _p;
final v = (_d * y2 + BigInt.one) % _p;
final v3 = v * v % _p * v % _p;
final v7 = v3 * v3 % _p * v % _p;
var x =
u * v3 % _p * (u * v7 % _p).modPow((_p - BigInt.from(5)) >> 3, _p) % _p;
final check = v * x % _p * x % _p;
if (check == u) {
// x is a square root of u/v.
} else if (check == (_p - u) % _p) {
x = x * _sqrtMinusOne % _p;
} else {
return null;
}
if (x == BigInt.zero && sign == 1) return null;
if (x.isOdd != (sign == 1)) x = _p - x;
return _Point(x, y, BigInt.one, x * y % _p);
}
List<int> _encode(_Point point) {
final inverse = point.z.modInverse(_p);
final x = point.x * inverse % _p;
final y = point.y * inverse % _p;
final out = _bytes(y);
if (x.isOdd) out[31] |= 0x80;
return out;
}
// The unified addition law (RFC 8032 section 5.1.4); it also doubles.
_Point _add(_Point p, _Point q) {
final a = (p.y - p.x) * (q.y - q.x) % _p;
final b = (p.y + p.x) * (q.y + q.x) % _p;
final c = p.t * BigInt.two * _d % _p * q.t % _p;
final d = p.z * BigInt.two * q.z % _p;
final e = (b - a) % _p, f = (d - c) % _p, g = (d + c) % _p, h = (b + a) % _p;
return _Point(e * f % _p, g * h % _p, f * g % _p, e * h % _p);
}
_Point _multiply(_Point point, BigInt scalar) {
var result = _identity;
var addend = point;
var rest = scalar;
while (rest > BigInt.zero) {
if (rest.isOdd) result = _add(result, addend);
addend = _add(addend, addend);
rest >>= 1;
}
return result;
}
bool _equal(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
@@ -0,0 +1,79 @@
import 'dart:convert';
import 'ed25519.dart';
/// The Ed25519 public keys this build trusts to sign update feeds, base64
/// and comma separated (`--dart-define=PIPELINES_UPDATE_PUBLIC_KEY`). The
/// installer embeds its own key and any listed in
/// `~/.config/pipelines/update-trusted-keys`; see
/// docs/notes/network-and-update-signing.md.
const embeddedUpdateKeys = String.fromEnvironment(
'PIPELINES_UPDATE_PUBLIC_KEY',
);
/// The trusted keys in [configured]; a malformed entry is dropped (the
/// installer refuses to build with one), and an empty result means this is
/// an unsigned development build.
List<List<int>> trustedUpdateKeys([String configured = embeddedUpdateKeys]) {
final keys = <List<int>>[];
for (final entry in configured.split(',')) {
final text = entry.trim();
if (text.isEmpty) continue;
try {
final key = base64.decode(text);
if (key.length == 32) keys.add(key);
} on FormatException {
continue;
}
}
return keys;
}
/// Why the [feed] bytes cannot be trusted, or null when they can.
///
/// [signatureDocument] is the detached `version.json.sig`
/// (`{"algorithm":"ed25519","publicKey":…,"signature":…}`), null when the
/// server offers none. A build with no trusted keys accepts any feed, as
/// before signing existed; a build with keys requires a valid signature by
/// one of them.
String? feedSignatureProblem(
List<int> feed,
String? signatureDocument,
List<List<int>> trusted,
) {
if (trusted.isEmpty) return null;
if (signatureDocument == null) {
return 'The update feed is not signed, so it was not trusted.';
}
final Object? document;
try {
document = jsonDecode(signatureDocument);
} on FormatException {
return 'The update feed signature is unreadable.';
}
if (document is! Map || document['algorithm'] != 'ed25519') {
return 'The update feed signature is unreadable.';
}
final List<int> key, signature;
try {
key = base64.decode('${document['publicKey'] ?? ''}');
signature = base64.decode('${document['signature'] ?? ''}');
} on FormatException {
return 'The update feed signature is unreadable.';
}
if (!trusted.any((candidate) => _same(candidate, key))) {
return 'The update feed is signed by a key this app does not trust.';
}
if (!ed25519Verify(publicKey: key, message: feed, signature: signature)) {
return 'The update feed signature does not match; it was not trusted.';
}
return null;
}
bool _same(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}