fix(#610): apply Gemini review, harden the card parser and chip

Three accepted findings, plus a real defect the adversarial test cases
flushed out.

A long name overflowed the chip by 405 pixels. The name comes off a
public radio channel and is attacker-controlled, so anyone could break a
message list by posting a card with a long name. The label is now
bounded and ellipsized, with an explicit width ceiling because a
WidgetSpan hands its child unbounded width.

fromChannelShare no longer scans from the first < to the last >. Two
cards in one message were read as a single span running from the first
key to the last name. That was reachable: the add dialog passes raw
pasted text straight to it. It now takes the first well-formed card via
a regex whose name class cannot cross a closing bracket.

The known-contact check is O(1) against the connector's existing
_knownContactKeys set, through a new isKnownContact. Scanning contacts
ran per chip on every notification, and the public knownContactKeys
getter copies the whole set, so neither belonged in a build method.

Card-versus-mention is now carried on the match instead of inferred from
text[m.start] == '<', which would mis-route the day a third bracketed
pattern is added.

Two findings were rejected on evidence and are justified in the PR body:
a claimed missing null terminator (firmware sets it from the frame
length itself) and a claimed greedy-regex failure (disproven by test).

Epic #610.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/610-contact-card-receive
Strycher 2 months ago committed by diffwireauto
parent cbb3703aba
commit af036fe6d1

@ -1036,6 +1036,15 @@ class MeshCoreConnector extends ChangeNotifier {
int get maxContacts => _maxContacts;
int get maxChannels => _maxChannels;
Set<String> get knownContactKeys => Set.unmodifiable(_knownContactKeys);
/// O(1) membership test for a contact by public key hex.
///
/// Use this from a widget `build`, never [knownContactKeys], which copies the
/// whole set on every call, nor a scan of [contacts]. A received contact card
/// asks this question once per rendered chip on every connector
/// notification. (#610)
bool isKnownContact(String publicKeyHex) =>
_knownContactKeys.contains(publicKeyHex);
double? get contactSyncProgress {
final total = _contactSyncTotal;
if (!_isLoadingContacts || total == null || total <= 0) return null;

@ -296,6 +296,13 @@ class Contact {
'&public_key=$publicKeyHex'
'&type=$type';
/// The body of one compact channel share, `<key:type:name>`, captured
/// without its delimiters. `[^>]*` cannot cross a closing bracket, so each
/// card matches individually even when several sit in one message.
static final RegExp _channelShareBody = RegExp(
r'<([0-9a-fA-F]{64}:\d+:[^>]*)>',
);
/// Compact contact share for a CHANNEL message, `<key:type:name>`. (#611)
///
/// This is a second, different format from [toShareUri], and deliberately so.
@ -338,12 +345,17 @@ class Contact {
/// Rendering a received card as a tappable Add Contact affordance is #610 and
/// is separate; this only handles text pasted or scanned into the add flow.
static Contact? fromChannelShare(String text) {
final trimmed = text.trim();
// Tolerate a card embedded in a longer message, which is how it arrives.
final start = trimmed.indexOf('<');
final end = trimmed.lastIndexOf('>');
if (start < 0 || end <= start) return null;
final body = trimmed.substring(start + 1, end);
// Tolerate a card embedded in a longer message, which is how it arrives,
// and take the FIRST well-formed one.
//
// Deliberately not a scan from the first `<` to the last `>`: a message
// carrying two cards would then be read as a single span running from the
// first key to the last name and parse as garbage. That is reachable,
// because the add dialog passes raw pasted text straight to here.
// (Gemini review, #610)
final match = _channelShareBody.firstMatch(text);
if (match == null) return null;
final body = match.group(1)!;
final firstColon = body.indexOf(':');
if (firstColon < 0) return null;

@ -39,41 +39,63 @@ class ContactCardChip extends StatelessWidget {
// Mirrors what stock does: it warned the owner when the contact was
// already held rather than silently re-adding.
//
// O(1) against the connector's maintained key set. Scanning `contacts`
// here would run per rendered chip on every notification, which is
// hundreds of comparisons in a message list on a device with a large
// contact book. (Gemini review, #610)
final known = context.select<MeshCoreConnector, bool>(
(c) => c.contacts.any((x) => x.publicKeyHex == parsed.publicKeyHex),
(c) => c.isKnownContact(parsed.publicKeyHex),
);
final label = known
? l10n.contacts_cardAlreadyAdded(parsed.name)
: l10n.contacts_cardAddContact(parsed.name);
final chip = Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: known
? scheme.onSurface.withValues(alpha: 0.08)
: scheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
known ? Icons.how_to_reg : Icons.person_add_alt_1,
size: 15,
color: known ? scheme.onSurfaceVariant : scheme.onPrimaryContainer,
),
const SizedBox(width: 5),
Text(
label,
style: style.copyWith(
fontWeight: FontWeight.w500,
// A WidgetSpan gives its child unbounded width, so Flexible needs a real
// ceiling to ellipsize against. Without this the chip grows to whatever
// name the sender chose.
final chip = ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 260),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: known
? scheme.onSurface.withValues(alpha: 0.08)
: scheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
known ? Icons.how_to_reg : Icons.person_add_alt_1,
size: 15,
color: known
? scheme.onSurfaceVariant
: scheme.onPrimaryContainer,
),
),
],
const SizedBox(width: 5),
// Bounded and ellipsized. The name comes off a public radio channel
// and is attacker-controlled, so an unbounded label lets anyone
// overflow the message layout by posting a card with a long name.
// Reproduced before this: a 405 pixel RenderFlex overflow.
// (Gemini review prompted the adversarial case, #610)
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: style.copyWith(
fontWeight: FontWeight.w500,
color: known
? scheme.onSurfaceVariant
: scheme.onPrimaryContainer,
),
),
),
],
),
),
);

@ -77,19 +77,21 @@ class TranslatedMessageContent extends StatelessWidget {
// Both patterns are collected and sorted by position, so a message
// carrying a mention AND a contact card renders both in the right order.
// They cannot overlap: a mention is `@[...]`, a card is `<...>`.
final matches = <Match>[
..._mention.allMatches(text),
..._contactCard.allMatches(text),
]..sort((a, b) => a.start.compareTo(b.start));
// Each match carries which pattern produced it. Inferring the kind from
// the text, e.g. `text[m.start] == '<'`, would silently mis-route the day
// a third bracketed pattern is added. (Gemini review, #610)
final matches = <(Match, bool isCard)>[
..._mention.allMatches(text).map((m) => (m, false)),
..._contactCard.allMatches(text).map((m) => (m, true)),
]..sort((a, b) => a.$1.start.compareTo(b.$1.start));
final spans = <InlineSpan>[];
var last = 0;
for (final m in matches) {
for (final (m, isCard) in matches) {
if (m.start < last) continue;
if (m.start > last) {
spans.add(TextSpan(text: text.substring(last, m.start)));
}
final isCard = text[m.start] == '<';
spans.add(
WidgetSpan(
alignment: PlaceholderAlignment.middle,

@ -4,38 +4,28 @@
// app showed a native Add Contact button for the very same payload. Sharing
// worked outbound only.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/widgets/translated_message_content.dart';
const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff';
const _card = '<$_key:1:Ka8sbi>';
class _Conn extends MeshCoreConnector {
_Conn({this.known = const []});
final List<Contact> known;
_Conn({this.known = const {}});
/// Public key hexes already in contacts. Mirrors the connector's own
/// `_knownContactKeys` set, which is what the chip now consults.
final Set<String> known;
@override
List<Contact> get contacts => known;
bool isKnownContact(String publicKeyHex) => known.contains(publicKeyHex);
}
Contact _contact(String keyHex) => Contact(
publicKey: hex2Uint8List(keyHex),
name: 'Ka8sbi',
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime(2026, 9, 9),
);
Future<void> _pump(WidgetTester tester, String text, _Conn conn) =>
tester.pumpWidget(
ChangeNotifierProvider<MeshCoreConnector>.value(
@ -72,7 +62,7 @@ void main() {
tester,
) async {
// Mirrors stock, which warned rather than silently re-adding.
await _pump(tester, _card, _Conn(known: [_contact(_key)]));
await _pump(tester, _card, _Conn(known: {_key}));
expect(find.byIcon(Icons.how_to_reg), findsOneWidget);
expect(find.byIcon(Icons.person_add_alt_1), findsNothing);
@ -113,6 +103,40 @@ void main() {
expect(find.textContaining('just a normal message'), findsOneWidget);
});
testWidgets('two cards in one message render as two separate chips', (
tester,
) async {
// Regression for the Gemini review: parsing from the first `<` to the last
// `>` would have read this as one span running from the first key to the
// second name, and produced garbage.
const other =
'ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100';
await _pump(tester, '$_card and <$other:2:Bob>', _Conn());
expect(find.byIcon(Icons.person_add_alt_1), findsNWidgets(2));
expect(find.textContaining('Ka8sbi'), findsOneWidget);
expect(find.textContaining('Bob'), findsOneWidget);
expect(find.textContaining(_key), findsNothing);
});
testWidgets('a nested bracket mess yields one card, and it is the outer key', (
tester,
) async {
// Adversarial input from a public channel. `[^>]*` cannot cross a `>`, so
// the match ends at the inner closing bracket and the nested text becomes
// part of the OUTER card's name. Exactly one add is offered, for the outer
// key, and the tap opens the dialog where the key is visible before
// anything is written to the radio. No second key is silently smuggled in.
const other =
'ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100';
await _pump(tester, '<$_key:1:Name <$other:2:Inner>>', _Conn());
expect(find.byIcon(Icons.person_add_alt_1), findsOneWidget);
// The parser took the outer card, so the nested text is shown as the name
// rather than being treated as a second identity.
expect(find.textContaining('Name <'), findsOneWidget);
});
testWidgets('names with spaces and emoji survive into the chip label', (
tester,
) async {

Loading…
Cancel
Save

Powered by TurnKey Linux.