Merge pull request #642 from zjs81/fix/tester-feedback

Address tester feedback; verify advert signatures
This commit is contained in:
zjs81 authored and GitHub committed 2026-11-07 19:24:33 -07:00
commit 89e2e07c05
52 files changed
+565 -129

No files matched your search

+43 -90
View File
@@ -9,6 +9,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
import '../utils/advert_signature.dart';
import '../models/channel.dart';
import '../models/channel_message.dart';
import '../models/companion_radio_stats.dart';
@@ -6433,6 +6434,13 @@ class MeshCoreConnector extends ChangeNotifier {
_contactsStorageFull = false; // capacity freed up since the warning
}
_hasLoadedContacts = true;
if (!_preserveContactsOnRefresh && !_contactSyncUsesSinceFilter) {
// A full sync replaced _contacts; drop keys the radio no longer
// holds so removed nodes reappear in discovery.
_knownContactKeys
..clear()
..addAll(_contacts.map((c) => c.publicKeyHex));
}
_preserveContactsOnRefresh = false;
_telemetryFixesDuringSync.clear();
_contactSyncUsesSinceFilter = false;
@@ -9383,13 +9391,15 @@ class MeshCoreConnector extends ChangeNotifier {
final rawPacket = frame.sublist(3);
switch (payloadType) {
case payloadTypeADVERT:
_handlePayloadAdvertReceived(
rawPacket,
payload,
pathBytes,
pathHashWidth,
routeType,
snr,
unawaited(
_verifyThenHandleAdvert(
rawPacket,
payload,
pathBytes,
pathHashWidth,
routeType,
snr,
),
);
break;
default:
@@ -9400,89 +9410,32 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
void importContact(Uint8List frame) {
final packet = BufferReader(frame);
int payloadType = 0;
Uint8List pathBytes = Uint8List(0);
int pathHashWidth = 1;
try {
packet.skipBytes(1); // Skip frame type byte
packet.skipBytes(1); // Skip SNR byte
packet.skipBytes(1); // Skip RSSI byte
final header = packet.readByte();
final routeType = header & 0x03;
payloadType = (header >> 2) & 0x0F;
if (routeType == _routeTransportFlood ||
routeType == _routeTransportDirect) {
packet.skipBytes(4); // Skip transport-specific bytes
}
//final payloadVer = (header >> 6) & 0x03;
final pathLenRaw = packet.readByte();
final pathByteLen = decodePathByteLen(pathLenRaw);
pathHashWidth = decodePathHashWidth(pathLenRaw);
pathBytes = packet.readBytes(pathByteLen);
} catch (e) {
appLogger.warn('Malformed RX frame: $e', tag: 'Connector');
/// Drops adverts whose Ed25519 signature does not verify against the
/// advertised public key, so forged adverts cannot add or update a contact
/// of any type (chat, repeater, room, sensor).
Future<void> _verifyThenHandleAdvert(
Uint8List rawPacket,
Uint8List payload,
Uint8List path,
int pathHashWidth,
int routeType,
double snr,
) async {
if (!await verifyAdvertSignature(payload)) {
appLogger.warn(
'Dropped advert with invalid signature'
'${payload.length >= 4 ? ' from ${pubKeyToHex(payload.sublist(0, 4))}' : ''}',
tag: 'Connector',
);
return;
}
double? latitude;
double? longitude;
String name = '';
Uint8List publicKey = Uint8List(0);
int type = 0;
int timestamp = 0;
bool hasLocation = false;
bool hasName = false;
if (payloadType != payloadTypeADVERT) {
appLogger.warn('Unexpected payload type: $payloadType', tag: 'Connector');
return;
}
try {
publicKey = packet.readBytes(32);
timestamp = packet.readInt32LE();
//TODO add signature verification
packet.skipBytes(64); // Skip signature for now
final flags = packet.readByte();
type = flags & 0x0F;
hasLocation = (flags & 0x10) != 0;
hasName = (flags & 0x80) != 0;
if (hasLocation && packet.remaining >= 8) {
latitude = packet.readInt32LE() / 1e6;
longitude = packet.readInt32LE() / 1e6;
}
// Two optional 16-bit feature fields sit between the location and the
// name (AdvertDataParser in MeshCore AdvertDataHelpers.cpp). Skip them
// so their bytes aren't read as the start of the name.
for (final featureMask in const [0x20, 0x40]) {
if ((flags & featureMask) != 0 && packet.remaining >= 2) {
packet.skipBytes(2);
}
}
if (hasName && packet.remaining > 0) {
name = packet.readCString();
}
} catch (e) {
appLogger.warn('Malformed advert frame: $e', tag: 'Connector');
return;
}
importDiscoveredContact(
Contact(
rawPacket: frame,
publicKey: publicKey,
name: name,
type: type,
pathLength: pathBytes.isEmpty
? -1
: (pathBytes.length ~/ pathHashWidth),
// Store hop order reversed for easier outgoing messages; keep bytes
// inside each multi-byte hop in their original order.
path: _reversePathByHop(pathBytes, pathHashWidth),
pathHashWidth: pathHashWidth,
latitude: latitude,
longitude: longitude,
lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
),
_handlePayloadAdvertReceived(
rawPacket,
payload,
path,
pathHashWidth,
routeType,
snr,
);
}
@@ -9522,8 +9475,8 @@ class MeshCoreConnector extends ChangeNotifier {
.join();
timestamp = advert.readInt32LE();
//TODO add signature verification
advert.skipBytes(64); // Skip signature for now
// Signature already checked by _verifyThenHandleAdvert.
advert.skipBytes(signatureSize);
final flags = advert.readByte();
type = flags & 0x0F;
hasLocation = (flags & 0x10) != 0;
+1
View File
@@ -1017,6 +1017,7 @@
"repeater_received": "Получено",
"repeater_duplicates": "Дубликати",
"repeater_daysHoursMinsSecs": "{days} дни {hours}ч {minutes}м {seconds}с",
"repeater_hoursMinsSecs": "{hours}ч {minutes}м {seconds}с",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1039,6 +1039,7 @@
"repeater_received": "Empfangen",
"repeater_duplicates": "Duplikate",
"repeater_daysHoursMinsSecs": "{days} Tage {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+14
View File
@@ -1716,6 +1716,20 @@
}
}
},
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_hoursMinsSecs": {
"placeholders": {
"hours": {
"type": "int"
},
"minutes": {
"type": "int"
},
"seconds": {
"type": "int"
}
}
},
"repeater_packetTxTotal": "Total: {total}, Flood: {flood}, Direct: {direct}",
"@repeater_packetTxTotal": {
"placeholders": {
+1
View File
@@ -1031,6 +1031,7 @@
"repeater_received": "Recibidos",
"repeater_duplicates": "Duplicados",
"repeater_daysHoursMinsSecs": "{days} días {hours}h {minutes} min {seconds} s",
"repeater_hoursMinsSecs": "{hours}h {minutes} min {seconds} s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1031,6 +1031,7 @@
"repeater_received": "Reçu",
"repeater_duplicates": "Doublons",
"repeater_daysHoursMinsSecs": "{days} jours {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1245,6 +1245,7 @@
"repeater_received": "Fogadva",
"repeater_duplicates": "Ismétlődések",
"repeater_daysHoursMinsSecs": "{days} nap {hours}ó {minutes}p {seconds}s",
"repeater_hoursMinsSecs": "{hours}ó {minutes}p {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1076,6 +1076,7 @@
"repeater_received": "Ricevuto",
"repeater_duplicates": "Duplicati",
"repeater_daysHoursMinsSecs": "{days} giorni {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+2 -1
View File
@@ -1213,6 +1213,7 @@
"repeater_received": "受信済み",
"repeater_duplicates": "重複",
"repeater_daysHoursMinsSecs": "{days}日 {hours}時間 {minutes}分 {seconds}秒",
"repeater_hoursMinsSecs": "{hours}時間 {minutes}分 {seconds}秒",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
@@ -1257,7 +1258,7 @@
}
}
},
"repeater_duplicatesFloodDirect": "{flood}: {flood}, 直接: {direct}",
"repeater_duplicatesFloodDirect": "フラッド: {flood}, 直接: {direct}",
"@repeater_duplicatesFloodDirect": {
"placeholders": {
"flood": {
+1
View File
@@ -1195,6 +1195,7 @@
"repeater_received": "수신",
"repeater_duplicates": "중복",
"repeater_daysHoursMinsSecs": "{days}일 {hours}시간 {minutes}분 {seconds}초",
"repeater_hoursMinsSecs": "{hours}시간 {minutes}분 {seconds}초",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+6
View File
@@ -5654,6 +5654,12 @@ abstract class AppLocalizations {
int seconds,
);
/// No description provided for @repeater_hoursMinsSecs.
///
/// In en, this message translates to:
/// **'{hours}h {minutes}m {seconds}s'**
String repeater_hoursMinsSecs(int hours, int minutes, int seconds);
/// No description provided for @repeater_packetTxTotal.
///
/// In en, this message translates to:
+5
View File
@@ -3206,6 +3206,11 @@ class AppLocalizationsBg extends AppLocalizations {
return '$days дни $hoursч $minutesм $secondsс';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hoursч $minutesм $secondsс';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Общо: $total, Flood: $flood, Директно: $direct';
+5
View File
@@ -3205,6 +3205,11 @@ class AppLocalizationsDe extends AppLocalizations {
return '$days Tage ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Gesamt: $total, Flood: $flood, Direkt: $direct';
+5
View File
@@ -3154,6 +3154,11 @@ class AppLocalizationsEn extends AppLocalizations {
return '$days days ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Total: $total, Flood: $flood, Direct: $direct';
+5
View File
@@ -3193,6 +3193,11 @@ class AppLocalizationsEs extends AppLocalizations {
return '$days días ${hours}h $minutes min $seconds s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h $minutes min $seconds s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Total: $total, Inundación: $flood, Directo: $direct';
+5
View File
@@ -3204,6 +3204,11 @@ class AppLocalizationsFr extends AppLocalizations {
return '$days jours ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Total : $total, Tout le réseau : $flood, Direct : $direct';
+5
View File
@@ -3195,6 +3195,11 @@ class AppLocalizationsHu extends AppLocalizations {
return '$days nap $hoursó ${minutes}p ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hoursó ${minutes}p ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Összesen: $total, Elárasztás: $flood, Közvetlen: $direct';
+5
View File
@@ -3201,6 +3201,11 @@ class AppLocalizationsIt extends AppLocalizations {
return '$days giorni ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Totale: $total, Flood: $flood, Diretto: $direct';
+6 -1
View File
@@ -3066,6 +3066,11 @@ class AppLocalizationsJa extends AppLocalizations {
return '$days日 $hours時間 $minutes分 $seconds秒';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours時間 $minutes分 $seconds秒';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return '合計: $total, フラッド: $flood, 直接: $direct';
@@ -3078,7 +3083,7 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String repeater_duplicatesFloodDirect(String flood, String direct) {
return '$flood: $flood, 直接: $direct';
return 'フラッド: $flood, 直接: $direct';
}
@override
+5
View File
@@ -3070,6 +3070,11 @@ class AppLocalizationsKo extends AppLocalizations {
return '$days일 $hours시간 $minutes분 $seconds초';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours시간 $minutes분 $seconds초';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return '총: $total, 플러딩: $flood, 직접: $direct';
+5
View File
@@ -3182,6 +3182,11 @@ class AppLocalizationsNl extends AppLocalizations {
return '$days dagen $hours uur $minutes minuten $seconds seconden';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours uur $minutes minuten $seconds seconden';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Totaal: $total, Flood: $flood, Direct: $direct';
+5
View File
@@ -3219,6 +3219,11 @@ class AppLocalizationsPl extends AppLocalizations {
return '$days dni ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Razem: $total, Flood: $flood, Bezpośrednio: $direct';
+5
View File
@@ -3194,6 +3194,11 @@ class AppLocalizationsPt extends AppLocalizations {
return '$days dias ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Total: $total, Inundação: $flood, Direto: $direct';
+5
View File
@@ -3200,6 +3200,11 @@ class AppLocalizationsRu extends AppLocalizations {
return '$days дн. $hoursч $minutesм $secondsс';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hoursч $minutesм $secondsс';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Всего: $total, Рассылка: $flood, Прямые: $direct';
+5
View File
@@ -3191,6 +3191,11 @@ class AppLocalizationsSk extends AppLocalizations {
return '$days dní ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Celkom: $total, Flood: $flood, Priame: $direct';
+5
View File
@@ -3184,6 +3184,11 @@ class AppLocalizationsSl extends AppLocalizations {
return '$days dni ${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '${hours}h ${minutes}m ${seconds}s';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Skupno: $total, Flood: $flood, Neposredno: $direct';
+5
View File
@@ -3170,6 +3170,11 @@ class AppLocalizationsSv extends AppLocalizations {
return '$days dagar $hours timmar $minutes minuter $seconds sekunder';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours timmar $minutes minuter $seconds sekunder';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Totalt: $total, Flood: $flood, Direkt: $direct';
+5
View File
@@ -3193,6 +3193,11 @@ class AppLocalizationsUk extends AppLocalizations {
return '$days дн. $hours год $minutes хв $seconds с';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours год $minutes хв $seconds с';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return 'Всього: $total, Через всю мережу: $flood, Прямі: $direct';
+5
View File
@@ -3025,6 +3025,11 @@ class AppLocalizationsZh extends AppLocalizations {
return '$days天 $hours小时 $minutes分 $seconds秒';
}
@override
String repeater_hoursMinsSecs(int hours, int minutes, int seconds) {
return '$hours小时 $minutes分 $seconds秒';
}
@override
String repeater_packetTxTotal(int total, String flood, String direct) {
return '总计:$total,泛洪:$flood,直连:$direct';
+1
View File
@@ -1044,6 +1044,7 @@
"repeater_received": "Ontvangen",
"repeater_duplicates": "Duplicaten",
"repeater_daysHoursMinsSecs": "{days} dagen {hours} uur {minutes} minuten {seconds} seconden",
"repeater_hoursMinsSecs": "{hours} uur {minutes} minuten {seconds} seconden",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1027,6 +1027,7 @@
"repeater_received": "Otrzymano",
"repeater_duplicates": "Powtórzenia",
"repeater_daysHoursMinsSecs": "{days} dni {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1009,6 +1009,7 @@
"repeater_received": "Recebido",
"repeater_duplicates": "Duplicatas",
"repeater_daysHoursMinsSecs": "{days} dias {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -627,6 +627,7 @@
"repeater_received": "Получено",
"repeater_duplicates": "Дубликаты",
"repeater_daysHoursMinsSecs": "{days} дн. {hours}ч {minutes}м {seconds}с",
"repeater_hoursMinsSecs": "{hours}ч {minutes}м {seconds}с",
"repeater_packetTxTotal": "Всего: {total}, Рассылка: {flood}, Прямые: {direct}",
"repeater_packetRxTotal": "Всего: {total}, Рассылка: {flood}, Прямые: {direct}",
"repeater_duplicatesFloodDirect": "Рассылка: {flood}, Прямые: {direct}",
+1
View File
@@ -1017,6 +1017,7 @@
"repeater_received": "Prijaté",
"repeater_duplicates": "Duplikáty",
"repeater_daysHoursMinsSecs": "{days} dní {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1009,6 +1009,7 @@
"repeater_received": "Prejeto",
"repeater_duplicates": "Duplikati",
"repeater_daysHoursMinsSecs": "{days} dni {hours}h {minutes}m {seconds}s",
"repeater_hoursMinsSecs": "{hours}h {minutes}m {seconds}s",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1010,6 +1010,7 @@
"repeater_received": "Mottaget",
"repeater_duplicates": "Dubbletter",
"repeater_daysHoursMinsSecs": "{days} dagar {hours} timmar {minutes} minuter {seconds} sekunder",
"repeater_hoursMinsSecs": "{hours} timmar {minutes} minuter {seconds} sekunder",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1027,6 +1027,7 @@
"repeater_received": "Отримано",
"repeater_duplicates": "Дублікати",
"repeater_daysHoursMinsSecs": "{days} дн. {hours} год {minutes} хв {seconds} с",
"repeater_hoursMinsSecs": "{hours} год {minutes} хв {seconds} с",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -1039,6 +1039,7 @@
"repeater_received": "接收",
"repeater_duplicates": "重复",
"repeater_daysHoursMinsSecs": "{days}天 {hours}小时 {minutes}分 {seconds}秒",
"repeater_hoursMinsSecs": "{hours}小时 {minutes}分 {seconds}秒",
"@repeater_daysHoursMinsSecs": {
"placeholders": {
"days": {
+1
View File
@@ -697,6 +697,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
}
void _handleQuickSwitch(int index, BuildContext context) {
FocusManager.instance.primaryFocus?.unfocus();
if (index == 1) return;
switch (index) {
case 0:
+10 -2
View File
@@ -795,7 +795,7 @@ class _ContactsScreenState extends State<ContactsScreen>
),
],
child: SizedBox(
height: 48,
height: _controlHeight(context),
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).colorScheme.outline),
@@ -821,6 +821,13 @@ class _ContactsScreenState extends State<ContactsScreen>
);
}
/// Height of the group/search controls; grows with the system font size so
/// larger text is not clipped.
double _controlHeight(BuildContext context) {
final textHeight = MediaQuery.textScalerOf(context).scale(16) * 1.5;
return (textHeight + 20).clamp(48.0, 120.0);
}
Widget _buildContactsBody(BuildContext context, MeshCoreConnector connector) {
final viewState = context.watch<UiViewStateService>();
final contacts = connector.contacts;
@@ -958,7 +965,7 @@ class _ContactsScreenState extends State<ContactsScreen>
width: viewState.contactsSearchExpanded
? searchExpandedWidth
: searchCollapsedWidth,
height: 48,
height: _controlHeight(context),
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
@@ -1266,6 +1273,7 @@ class _ContactsScreenState extends State<ContactsScreen>
}
void _handleQuickSwitch(int index, BuildContext context) {
FocusManager.instance.primaryFocus?.unfocus();
if (index == 0) return;
switch (index) {
case 1:
@@ -1728,6 +1728,7 @@ class _LineOfSightMapScreenState extends State<LineOfSightMapScreen> {
}
void _handleQuickSwitch(int index, BuildContext context) {
FocusManager.instance.primaryFocus?.unfocus();
if (index == 2) {
Navigator.pop(context);
return;
+1
View File
@@ -3170,6 +3170,7 @@ class _MapScreenState extends State<MapScreen> with DisconnectNavigationMixin {
}
void _handleQuickSwitch(int index, BuildContext context) {
FocusManager.instance.primaryFocus?.unfocus();
if (index == 2) return;
switch (index) {
case 0:
@@ -178,6 +178,8 @@ class _RulesList extends StatelessWidget {
SnackBar(
content: Text(l10n.messageFilter_ruleDeleted),
duration: const Duration(seconds: 6),
// Newer Flutter persists snackbars with an action unless told not to.
persist: false,
action: SnackBarAction(
label: l10n.common_undo,
onPressed: () =>
+16 -4
View File
@@ -374,15 +374,24 @@ class _RepeaterStatusScreenState extends State<RepeaterStatusScreen> {
final hours = (seconds % 86400) ~/ 3600;
final minutes = (seconds % 3600) ~/ 60;
final secs = seconds % 60;
if (days == 0) return l10n.repeater_hoursMinsSecs(hours, minutes, secs);
return l10n.repeater_daysHoursMinsSecs(days, hours, minutes, secs);
}
/// Puts each "Label: n" part of a multi-part stat on its own line. Matches
/// the comma separators used across locales (ASCII, fullwidth, ideographic,
/// Arabic); the values themselves are unformatted integers.
static final _partSeparator = RegExp(r'\s*[,\uFF0C\u3001\u060C]\s*');
String _multiLine(String text) => text.split(_partSeparator).join('\n');
String _packetTxText() {
if (_packetsSent == null) return '—';
final l10n = context.l10n;
final flood = _formatValue(_floodTx);
final direct = _formatValue(_directTx);
return l10n.repeater_packetTxTotal(_packetsSent!, flood, direct);
return _multiLine(
l10n.repeater_packetTxTotal(_packetsSent!, flood, direct),
);
}
String _packetRxText() {
@@ -390,7 +399,9 @@ class _RepeaterStatusScreenState extends State<RepeaterStatusScreen> {
final l10n = context.l10n;
final flood = _formatValue(_floodRx);
final direct = _formatValue(_directRx);
return l10n.repeater_packetRxTotal(_packetsRecv!, flood, direct);
return _multiLine(
l10n.repeater_packetRxTotal(_packetsRecv!, flood, direct),
);
}
String _chanUtilText() {
@@ -403,7 +414,7 @@ class _RepeaterStatusScreenState extends State<RepeaterStatusScreen> {
if (_dupFlood != null || _dupDirect != null) {
final flood = _formatValue(_dupFlood);
final direct = _formatValue(_dupDirect);
return l10n.repeater_duplicatesFloodDirect(flood, direct);
return _multiLine(l10n.repeater_duplicatesFloodDirect(flood, direct));
}
if (_packetsRecv == null || _floodRx == null || _directRx == null) {
return '—';
@@ -702,7 +713,8 @@ class _RepeaterStatusScreenState extends State<RepeaterStatusScreen> {
final textScaler = MediaQuery.textScalerOf(context);
return LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth / textScaler.scale(1) < 320
// One full-width tile per row on phones; two columns on wide screens.
final columns = constraints.maxWidth / textScaler.scale(1) < 520
? 1
: 2;
// Rows size to their tallest tile, so labels that wrap at large
+4 -2
View File
@@ -558,7 +558,7 @@ class MeshTheme {
return TextStyle(
fontFamily: MeshFonts.sans,
fontFamilyFallback: MeshFonts.sansFallback,
fontSize: 11.5,
fontSize: 12,
fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
letterSpacing: 0.1,
color: selected ? scheme.onPrimary : scheme.onSurfaceVariant,
@@ -591,7 +591,9 @@ class MeshTheme {
),
snackBarTheme: SnackBarThemeData(
backgroundColor: scheme.surfaceContainerHigh,
contentTextStyle: TextStyle(color: scheme.onSurface),
contentTextStyle: TextStyle(color: scheme.onSurface, fontSize: 16),
actionTextColor: scheme.onSurface,
disabledActionTextColor: scheme.onSurfaceVariant,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(MeshRadii.md),
+73
View File
@@ -0,0 +1,73 @@
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
/// Advert payload layout (MeshCore `Mesh::createAdvert`):
/// `[pub_key 32][timestamp u32 LE][signature 64][app_data …]`.
const int _pubKeyLen = 32;
const int _timestampLen = 4;
const int _signatureLen = 64;
const int advertSignedHeaderLen = _pubKeyLen + _timestampLen + _signatureLen;
final Ed25519 _ed25519 = Ed25519();
/// Verified results keyed by signature, so the same advert heard over
/// several paths is only checked once.
final Map<String, bool> _verifiedCache = <String, bool>{};
const int _verifiedCacheMax = 256;
/// Returns true when [payload] is an advert whose Ed25519 signature over
/// `pub_key || timestamp || app_data` verifies against its own public key.
/// Applies to every advert type (chat, repeater, room, sensor).
Future<bool> verifyAdvertSignature(Uint8List payload) async {
if (payload.length < advertSignedHeaderLen) return false;
final publicKey = Uint8List.sublistView(payload, 0, _pubKeyLen);
final timestamp = Uint8List.sublistView(
payload,
_pubKeyLen,
_pubKeyLen + _timestampLen,
);
final signature = Uint8List.sublistView(
payload,
_pubKeyLen + _timestampLen,
advertSignedHeaderLen,
);
final appData = Uint8List.sublistView(payload, advertSignedHeaderLen);
final cacheKey =
String.fromCharCodes(publicKey) + String.fromCharCodes(signature);
final cached = _verifiedCache[cacheKey];
if (cached != null) return cached;
final message = Uint8List(_pubKeyLen + _timestampLen + appData.length)
..setRange(0, _pubKeyLen, publicKey)
..setRange(_pubKeyLen, _pubKeyLen + _timestampLen, timestamp)
..setRange(
_pubKeyLen + _timestampLen,
_pubKeyLen + _timestampLen + appData.length,
appData,
);
bool valid;
try {
valid = await _ed25519.verify(
message,
signature: Signature(
Uint8List.fromList(signature),
publicKey: SimplePublicKey(
Uint8List.fromList(publicKey),
type: KeyPairType.ed25519,
),
),
);
} catch (_) {
valid = false;
}
if (_verifiedCache.length >= _verifiedCacheMax) {
_verifiedCache.remove(_verifiedCache.keys.first);
}
_verifiedCache[cacheKey] = valid;
return valid;
}
+3 -6
View File
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
/// App bar title that honors the system font size. Long titles are
/// ellipsized instead of being shrunk to fit.
class AdaptiveAppBarTitle extends StatelessWidget {
final String text;
@@ -7,11 +9,6 @@ class AdaptiveAppBarTitle extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => SizedBox(
width: constraints.maxWidth,
child: FittedBox(fit: BoxFit.scaleDown, child: Text(text, maxLines: 1)),
),
);
return Text(text, maxLines: 1, overflow: TextOverflow.ellipsis);
}
}
+13
View File
@@ -100,6 +100,11 @@ class _FilterRuleDialogState extends State<_FilterRuleDialog> {
content: SizedBox(
width: 420,
child: SingleChildScrollView(
// The outlined field's floating label is painted above the field's
// box, outside the scroll content bounds. Without top padding the
// viewport clips it (worst when the focused field is scrolled flush
// to the top while the keyboard is open).
padding: const EdgeInsets.only(top: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -107,6 +112,14 @@ class _FilterRuleDialogState extends State<_FilterRuleDialog> {
TextField(
controller: _controller,
autofocus: true,
// Keep room above the field when it is scrolled into view, so
// the floating label (drawn above the box) is not clipped.
scrollPadding: EdgeInsets.fromLTRB(
20,
16 + MediaQuery.textScalerOf(context).scale(16),
20,
20,
),
minLines: 1,
maxLines: 4,
textInputAction: TextInputAction.done,
+19 -23
View File
@@ -243,7 +243,7 @@ class StatTile extends StatelessWidget {
label.toUpperCase(),
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 12,
fontSize: 14,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -252,30 +252,26 @@ class StatTile extends StatelessWidget {
],
),
const SizedBox(height: 6),
FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerStart,
child: Text.rich(
TextSpan(
text: value,
style: MeshTheme.mono(
fontSize: 17,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
children: [
if (unit != null)
TextSpan(
text: ' $unit',
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
Text.rich(
TextSpan(
text: value,
style: MeshTheme.mono(
fontSize: 20,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
maxLines: 1,
children: [
if (unit != null)
TextSpan(
text: ' $unit',
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
),
softWrap: true,
),
],
),
+145
View File
@@ -0,0 +1,145 @@
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/utils/advert_signature.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Builds an advert payload signed the way MeshCore's Mesh::createAdvert does.
Future<Uint8List> _signedAdvert(
int seedByte, {
required int type,
required String name,
int timestamp = 1700000000,
}) async {
final algo = Ed25519();
final keys = await algo.newKeyPairFromSeed(List<int>.filled(32, seedByte));
final pub = (await keys.extractPublicKey()).bytes;
final ts = Uint8List(4)
..buffer.asByteData().setUint32(0, timestamp, Endian.little);
final appData = [0x80 | type, ...name.codeUnits];
final sig = await algo.sign([...pub, ...ts, ...appData], keyPair: keys);
return Uint8List.fromList([...pub, ...ts, ...sig.bytes, ...appData]);
}
/// Wraps an advert payload in a PUSH_CODE_LOG_RX_DATA frame (flood, no path).
List<int> _rxFrame(Uint8List payload) => [
pushCodeLogRxData,
0, // snr
0, // rssi
(payloadTypeADVERT << 2) | 0x01, // header: flood route
0, // path length
...payload,
];
List<int> _contactFrame(int code, List<int> key, String name) {
final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12);
final bytes = data.buffer.asUint8List();
bytes[0] = code;
bytes.setRange(1, 33, key);
bytes[33] = advTypeRepeater;
bytes[35] = 0xFF;
bytes.setRange(100, 100 + name.length, name.codeUnits);
data.setUint32(132, 1700000000, Endian.little);
return bytes;
}
Future<void> _settle() async {
for (var i = 0; i < 20; i++) {
await Future<void>.delayed(Duration.zero);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
group('verifyAdvertSignature', () {
for (final type in [
advTypeChat,
advTypeRepeater,
advTypeRoom,
advTypeSensor,
]) {
test('accepts a valid advert of type $type', () async {
final advert = await _signedAdvert(
type + 10,
type: type,
name: 'N$type',
);
expect(await verifyAdvertSignature(advert), isTrue);
});
}
test('rejects tampered app data', () async {
final advert = await _signedAdvert(1, type: advTypeRepeater, name: 'Rpt');
advert[advert.length - 1] ^= 0x01;
expect(await verifyAdvertSignature(advert), isFalse);
});
test('rejects a swapped public key', () async {
final advert = await _signedAdvert(2, type: advTypeChat, name: 'Bob');
final other = await _signedAdvert(3, type: advTypeChat, name: 'Bob');
advert.setRange(0, 32, other.sublist(0, 32));
expect(await verifyAdvertSignature(advert), isFalse);
});
test('rejects a short payload', () async {
expect(await verifyAdvertSignature(Uint8List(99)), isFalse);
});
});
group('RX advert handling', () {
test('valid advert is discovered', () async {
final connector = MeshCoreConnector();
final advert = await _signedAdvert(4, type: advTypeRoom, name: 'Room');
connector.handleFrameForTest(_rxFrame(advert));
await _settle();
expect(connector.discoveredContacts.map((c) => c.name), contains('Room'));
});
test('forged advert is dropped', () async {
final connector = MeshCoreConnector();
final advert = await _signedAdvert(
5,
type: advTypeRepeater,
name: 'Real',
);
// Rename without re-signing.
advert.setRange(advert.length - 4, advert.length, 'Fake'.codeUnits);
connector.handleFrameForTest(_rxFrame(advert));
await _settle();
expect(connector.discoveredContacts, isEmpty);
});
});
test('full contact sync forgets keys the radio dropped', () async {
final connector = MeshCoreConnector();
final kept = List<int>.generate(32, (i) => i + 1);
final dropped = List<int>.generate(32, (i) => 100 + i);
connector.handleFrameForTest([respCodeContactsStart, 0, 0, 0, 0]);
connector.handleFrameForTest(_contactFrame(respCodeContact, kept, 'Kept'));
connector.handleFrameForTest(
_contactFrame(respCodeContact, dropped, 'Gone'),
);
connector.handleFrameForTest([respCodeEndOfContacts, 0, 0, 0, 0]);
expect(connector.knownContactKeys.length, 2);
connector.handleFrameForTest([respCodeContactsStart, 0, 0, 0, 0]);
connector.handleFrameForTest(_contactFrame(respCodeContact, kept, 'Kept'));
connector.handleFrameForTest([respCodeEndOfContacts, 0, 0, 0, 0]);
await _settle();
expect(connector.contacts.map((c) => c.name), ['Kept']);
expect(connector.knownContactKeys, hasLength(1));
});
}
+57
View File
@@ -0,0 +1,57 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
double _contrast(Color a, Color b) {
final la = a.computeLuminance();
final lb = b.computeLuminance();
final hi = la > lb ? la : lb;
final lo = la > lb ? lb : la;
return (hi + 0.05) / (lo + 0.05);
}
void main() {
test('snackbar action text is readable in light and dark themes', () {
for (final theme in [MeshTheme.light(), MeshTheme.dark()]) {
final sb = theme.snackBarTheme;
expect(sb.actionTextColor, isNotNull);
expect(
_contrast(sb.actionTextColor!, sb.backgroundColor!),
greaterThanOrEqualTo(4.5),
);
}
});
testWidgets('snackbar with action and persist:false auto-dismisses', (
tester,
) async {
late BuildContext ctx;
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.light(),
home: Scaffold(
body: Builder(
builder: (c) {
ctx = c;
return const SizedBox();
},
),
),
),
);
ScaffoldMessenger.of(ctx).showSnackBar(
SnackBar(
content: const Text('Rule deleted'),
duration: const Duration(seconds: 6),
persist: false,
action: SnackBarAction(label: 'Undo', onPressed: () {}),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.text('Rule deleted'), findsOneWidget);
await tester.pump(const Duration(seconds: 7));
await tester.pumpAndSettle();
expect(find.text('Rule deleted'), findsNothing);
});
}
+48
View File
@@ -0,0 +1,48 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/widgets/filter_rule_dialog.dart';
void main() {
for (final scale in [1.0, 2.0]) {
testWidgets('floating label is not clipped with keyboard (scale $scale)', (
tester,
) async {
tester.view.physicalSize = const Size(1080, 1400);
tester.view.devicePixelRatio = 2.75;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) {
final mq = MediaQuery.of(context);
return MediaQuery(
data: mq.copyWith(
textScaler: TextScaler.linear(scale),
viewInsets: const EdgeInsets.only(bottom: 150),
),
child: child!,
);
},
home: Builder(
builder: (context) => TextButton(
onPressed: () => showFilterRuleDialog(context),
child: const Text('open'),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
final scrollRect = tester.getRect(find.byType(SingleChildScrollView));
final labelRect = tester.getRect(find.byType(InputDecorator));
// The floating label sits above the field box; the scroll viewport must
// start above the field with room for it.
final fieldTop = labelRect.top;
expect(fieldTop - scrollRect.top, greaterThanOrEqualTo(8 * scale));
});
}
}