From d4420aa752cb70c3cdb35fa7928218d20297dfd6 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:50:59 -0500 Subject: [PATCH 1/3] feat(#1289): one link handler for meshcore:// share links Every share link now goes through LinkRouter, which parses it and holds it until its confirmation can be shown. LinkRouterHost, wrapping the home route, shows that confirmation over whatever screen is open. Nothing is added without the user confirming. - Channel links open the channel-add confirmation, now shared with the QR scanner (confirmAndAddSharedChannel), which keeps the slot-after- confirm rule from #1021. - Contact links open the add-contact dialog, already filled in. - The older meshcore:// form that "Copy Advert to Clipboard" still produces is imported through the radio after a confirmation, the same as "Add Contact from Clipboard". - A hashtag link needs no secret: the key is derived from the name, and #public means the real Public channel. - With no radio connected, the link waits, with a persistent message, and its confirmation appears once a radio connects and, for a channel, the channel table has settled. Only the latest link is held, in memory only. - A malformed link gets a persistent message instead of nothing. - A meshcore:// link in a chat message is now tappable and opens this flow. Before, it was plain text: the URL linkifier only knows http(s). Regression tests: - channel_share_uri_test: hashtag links derive the reference app's keys. - link_router_test: parsing and the holding rules. - meshcore_linkifier_test: finding links in message text. - link_router_host_test: wait, confirm, cancel, duplicate, malformed, and a tap in a message. Against dev's parser and link handler, 7 of them fail. New strings are English only; untranslated.json updated. Epic: #1285 Feature: #1280 Agent: StormyElk (session 088ce922) --- lib/helpers/channel_share_add.dart | 69 ++++++++ lib/helpers/link_handler.dart | 50 +++++- lib/l10n/app_en.arb | 25 +++ lib/l10n/app_localizations.dart | 30 ++++ lib/l10n/app_localizations_bg.dart | 20 +++ lib/l10n/app_localizations_de.dart | 20 +++ lib/l10n/app_localizations_en.dart | 20 +++ lib/l10n/app_localizations_es.dart | 20 +++ lib/l10n/app_localizations_fr.dart | 20 +++ lib/l10n/app_localizations_hu.dart | 20 +++ lib/l10n/app_localizations_it.dart | 20 +++ lib/l10n/app_localizations_ja.dart | 20 +++ lib/l10n/app_localizations_ko.dart | 20 +++ lib/l10n/app_localizations_nl.dart | 20 +++ lib/l10n/app_localizations_pl.dart | 20 +++ lib/l10n/app_localizations_pt.dart | 20 +++ lib/l10n/app_localizations_ru.dart | 20 +++ lib/l10n/app_localizations_sk.dart | 20 +++ lib/l10n/app_localizations_sl.dart | 20 +++ lib/l10n/app_localizations_sv.dart | 20 +++ lib/l10n/app_localizations_uk.dart | 20 +++ lib/l10n/app_localizations_zh.dart | 20 +++ lib/main.dart | 9 +- lib/models/channel.dart | 26 ++- lib/screens/community_qr_scanner_screen.dart | 65 +------- lib/services/link_router.dart | 120 ++++++++++++++ lib/widgets/link_router_host.dart | 139 ++++++++++++++++ test/helpers/meshcore_linkifier_test.dart | 57 +++++++ test/models/channel_share_uri_test.dart | 31 ++++ test/services/link_router_test.dart | 110 +++++++++++++ test/widgets/link_router_host_test.dart | 163 +++++++++++++++++++ untranslated.json | 119 ++++++++++++-- 32 files changed, 1293 insertions(+), 80 deletions(-) create mode 100644 lib/helpers/channel_share_add.dart create mode 100644 lib/services/link_router.dart create mode 100644 lib/widgets/link_router_host.dart create mode 100644 test/helpers/meshcore_linkifier_test.dart create mode 100644 test/services/link_router_test.dart create mode 100644 test/widgets/link_router_host_test.dart diff --git a/lib/helpers/channel_share_add.dart b/lib/helpers/channel_share_add.dart new file mode 100644 index 00000000..be01f41c --- /dev/null +++ b/lib/helpers/channel_share_add.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../models/channel.dart'; +import 'channel_slot_ui.dart'; +import 'snack_bar_builder.dart'; + +enum SharedChannelAdd { added, alreadyExists, cancelled, refused } + +/// Asks the user to confirm adding a shared [channel], then writes it. +/// +/// Every way a shared channel arrives goes through here: a scanned QR, a +/// tapped link, a link handed over by the OS (#1289). The slot is chosen +/// after the user confirms, never before: a channel sync during the dialog +/// could otherwise leave it pointing at an occupied slot (#1021). +/// +/// A refusal has already been explained to the user when this returns +/// [SharedChannelAdd.refused], so the caller should not show anything over +/// it. +Future confirmAndAddSharedChannel( + BuildContext context, + Channel channel, +) async { + final connector = context.read(); + if (connector.channels.any((c) => c.pskHex == channel.pskHex)) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.channels_qrExists(channel.name)), + ); + return SharedChannelAdd.alreadyExists; + } + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.channels_addChannel), + content: Text(dialogContext.l10n.channels_qrAddConfirm(channel.name)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(dialogContext.l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(dialogContext.l10n.common_add), + ), + ], + ), + ); + if (confirmed != true || !context.mounted) return SharedChannelAdd.cancelled; + final slot = allocateChannelSlotOrExplain( + context, + connector, + psk: channel.psk, + ); + if (slot == null) return SharedChannelAdd.refused; + final result = await connector.setChannel(slot, channel.name, channel.psk); + if (!context.mounted) return SharedChannelAdd.refused; + if (explainUnconfirmedChannelWrite(context, result)) { + return SharedChannelAdd.refused; + } + showDismissibleSnackBar( + context, + content: Text(context.l10n.channels_qrAdded(channel.name)), + backgroundColor: Colors.green, + ); + return SharedChannelAdd.added; +} diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index 58e76cca..f4f6e9a1 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -1,10 +1,49 @@ import 'package:flutter/material.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; import '../l10n/l10n.dart'; +import '../services/link_router.dart'; import '../utils/platform_info.dart'; import '../helpers/snack_bar_builder.dart'; +/// Finds `meshcore://` share links in message text, which the stock URL +/// linkifier does not, since it only knows http(s) and www. (#1289) +class MeshcoreLinkifier extends Linkifier { + const MeshcoreLinkifier(); + + static final _link = RegExp(r'meshcore://[^\s<>"]+', caseSensitive: false); + static final _trailingPunctuation = RegExp(r'[.,;:!?]+$'); + + @override + List parse( + List elements, + LinkifyOptions options, + ) { + final out = []; + for (final element in elements) { + if (element is! TextElement) { + out.add(element); + continue; + } + final text = element.text; + var last = 0; + for (final match in _link.allMatches(text)) { + // A sentence ending right after a link keeps its full stop. + final url = match[0]!.replaceFirst(_trailingPunctuation, ''); + final end = match.start + url.length; + if (match.start > last) { + out.add(TextElement(text.substring(last, match.start))); + } + out.add(UrlElement(url)); + last = end; + } + if (last < text.length) out.add(TextElement(text.substring(last))); + } + return out; + } +} + class LinkHandler { static TextStyle defaultLinkStyle(BuildContext context, TextStyle base) { final brightness = Theme.of(context).brightness; @@ -18,7 +57,11 @@ class LinkHandler { humanize: false, defaultToHttps: false, ); - static const _linkifiers = [UrlLinkifier(), EmailLinkifier()]; + static const _linkifiers = [ + MeshcoreLinkifier(), + UrlLinkifier(), + EmailLinkifier(), + ]; /// Returns a [SelectableLinkify] on desktop or a [Linkify] on mobile. static Widget buildLinkifyText({ @@ -69,6 +112,11 @@ class LinkHandler { } static Future handleLinkTap(BuildContext context, String url) async { + // A share link opens Offband's own add confirmation, not the browser. + if (url.toLowerCase().startsWith('meshcore://')) { + context.read().handle(url); + return; + } // Show confirmation dialog final shouldOpen = await showDialog( context: context, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 49b03953..c65b1100 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3964,5 +3964,30 @@ "storage_resultFailed": "Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.", "@storage_resultFailed": { "description": "Shown when the clear threw. It must not claim nothing happened, because the sweep deletes per key and may have cleared some before failing (#962)." + }, + "link_invalid": "This link isn't a channel or contact that Offband can add.", + "@link_invalid": { + "description": "Persistent message when a tapped or opened meshcore:// link cannot be parsed (#1289)." + }, + "link_waitingForRadio": "Connect a radio to add {name}. You'll be asked to confirm once it's connected.", + "@link_waitingForRadio": { + "description": "Persistent message when a share link arrives with no radio connected. The link is held until a radio connects (#1289).", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "link_waitingForRadioContact": "Connect a radio to add this contact. You'll be asked to confirm once it's connected.", + "@link_waitingForRadioContact": { + "description": "As link_waitingForRadio, for a contact advert link, which carries no readable name (#1289)." + }, + "link_addContactTitle": "Add Contact", + "@link_addContactTitle": { + "description": "Title of the confirmation for a tapped contact advert link (#1289)." + }, + "link_importAdvertConfirm": "Add the contact in this link to your radio?", + "@link_importAdvertConfirm": { + "description": "Confirmation body for a tapped meshcore:// contact advert link. The name is inside the signed advert, so it cannot be shown here (#1289)." } } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index dd4adc19..3fdf1c75 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -10383,6 +10383,36 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'** String get storage_resultFailed; + + /// Persistent message when a tapped or opened meshcore:// link cannot be parsed (#1289). + /// + /// In en, this message translates to: + /// **'This link isn\'t a channel or contact that Offband can add.'** + String get link_invalid; + + /// Persistent message when a share link arrives with no radio connected. The link is held until a radio connects (#1289). + /// + /// In en, this message translates to: + /// **'Connect a radio to add {name}. You\'ll be asked to confirm once it\'s connected.'** + String link_waitingForRadio(String name); + + /// As link_waitingForRadio, for a contact advert link, which carries no readable name (#1289). + /// + /// In en, this message translates to: + /// **'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'** + String get link_waitingForRadioContact; + + /// Title of the confirmation for a tapped contact advert link (#1289). + /// + /// In en, this message translates to: + /// **'Add Contact'** + String get link_addContactTitle; + + /// Confirmation body for a tapped meshcore:// contact advert link. The name is inside the signed advert, so it cannot be shown here (#1289). + /// + /// In en, this message translates to: + /// **'Add the contact in this link to your radio?'** + String get link_importAdvertConfirm; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 7093a400..e85987a8 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -6234,4 +6234,24 @@ class AppLocalizationsBg extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 756e6f48..18d2095e 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -6251,4 +6251,24 @@ class AppLocalizationsDe extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index c48a6919..a1653a2a 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -6157,4 +6157,24 @@ class AppLocalizationsEn extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index d21093f6..7bd9e30a 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -6239,4 +6239,24 @@ class AppLocalizationsEs extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 60243406..9749cb44 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -6267,4 +6267,24 @@ class AppLocalizationsFr extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 16b86c41..ce93b4b3 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -6256,4 +6256,24 @@ class AppLocalizationsHu extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 67d9fce8..7e2d8a3b 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -6244,4 +6244,24 @@ class AppLocalizationsIt extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 5cf7e921..6e491c39 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -6010,4 +6010,24 @@ class AppLocalizationsJa extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 92df42e1..244f29aa 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -6011,4 +6011,24 @@ class AppLocalizationsKo extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index bc23f68b..356d0c51 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -6219,4 +6219,24 @@ class AppLocalizationsNl extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index bf3fcad3..25f55d30 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -6256,4 +6256,24 @@ class AppLocalizationsPl extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index ea6e17fe..c48fef97 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -6232,4 +6232,24 @@ class AppLocalizationsPt extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a784f57e..bdc29f7d 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -6250,4 +6250,24 @@ class AppLocalizationsRu extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index ce471d75..052566a2 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -6216,4 +6216,24 @@ class AppLocalizationsSk extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e76cc7e6..204a310b 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -6214,4 +6214,24 @@ class AppLocalizationsSl extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 34a51612..8d593686 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -6189,4 +6189,24 @@ class AppLocalizationsSv extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index a53b70cf..3938efb9 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -6251,4 +6251,24 @@ class AppLocalizationsUk extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index c1ac45a0..4dc83082 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5884,4 +5884,24 @@ class AppLocalizationsZh extends AppLocalizations { @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; + + @override + String get link_invalid => + 'This link isn\'t a channel or contact that Offband can add.'; + + @override + String link_waitingForRadio(String name) { + return 'Connect a radio to add $name. You\'ll be asked to confirm once it\'s connected.'; + } + + @override + String get link_waitingForRadioContact => + 'Connect a radio to add this contact. You\'ll be asked to confirm once it\'s connected.'; + + @override + String get link_addContactTitle => 'Add Contact'; + + @override + String get link_importAdvertConfirm => + 'Add the contact in this link to your radio?'; } diff --git a/lib/main.dart b/lib/main.dart index af5b2dc5..e806f7f1 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -22,6 +22,7 @@ import 'services/notification_service.dart'; import 'services/ble_debug_log_service.dart'; import 'services/app_debug_log_service.dart'; import 'services/app_exit_info_service.dart'; +import 'services/link_router.dart'; import 'services/region_scope_banner_service.dart'; import 'services/failure_monitor.dart'; import 'services/file_log_service.dart'; @@ -48,6 +49,7 @@ import 'widgets/storage_unavailable_banner.dart'; import 'storage/prefs_manager.dart'; import 'utils/app_logger.dart'; import 'widgets/keep_screen_awake.dart'; +import 'widgets/link_router_host.dart'; import 'widgets/ios_on_mac_notice.dart'; import 'widgets/sponsor_prompt.dart'; @@ -361,6 +363,7 @@ class MeshCoreApp extends StatelessWidget { ChangeNotifierProvider.value(value: radioPresetService), ChangeNotifierProvider(create: (_) => ObserverConfigService(connector)), ChangeNotifierProvider(create: (_) => RegionScopeBannerService()), + ChangeNotifierProvider(create: (_) => LinkRouter()), ], child: Consumer( builder: (context, settingsService, child) { @@ -439,8 +442,10 @@ class MeshCoreApp extends StatelessWidget { }, home: (PlatformInfo.isWeb && !PlatformInfo.isChrome) ? const ChromeRequiredScreen() - : const IosOnMacNoticeGate( - child: SponsorPromptGate(child: ScannerScreen()), + : const LinkRouterHost( + child: IosOnMacNoticeGate( + child: SponsorPromptGate(child: ScannerScreen()), + ), ), ); }, diff --git a/lib/models/channel.dart b/lib/models/channel.dart index 79c8401e..1d784264 100644 --- a/lib/models/channel.dart +++ b/lib/models/channel.dart @@ -114,6 +114,10 @@ class Channel { /// Parses a channel from a reference-app share URI, or null if malformed. /// [index] is the local slot the caller assigns on add. (#161) + /// + /// A hashtag channel's key is derived from its name, so a link naming one + /// needs no `secret=`; "#public" means the real Public, as everywhere else + /// (#1896). (#1289) static Channel? fromShareUri(String uri, {int index = 0}) { final parsed = Uri.tryParse(uri.trim()); if (parsed == null || parsed.scheme != 'meshcore') return null; @@ -121,7 +125,8 @@ class Channel { if (parsed.path.replaceAll('/', '') != 'add') return null; final name = parsed.queryParameters['name']; final secret = parsed.queryParameters['secret']; - if (name == null || secret == null) return null; + if (name == null) return null; + if (secret == null) return _fromHashtagName(name, index); try { return Channel(index: index, name: name, psk: parsePskHex(secret)); } catch (_) { @@ -129,6 +134,25 @@ class Channel { } } + static Channel? _fromHashtagName(String name, int index) { + final trimmed = name.trim(); + if (!trimmed.startsWith('#')) return null; + final bare = trimmed.substring(1).trim(); + if (bare.isEmpty) return null; + if (hashtagMeansPublic(bare)) { + return Channel( + index: index, + name: 'Public', + psk: parsePskHex(publicChannelPsk), + ); + } + return Channel( + index: index, + name: '#$bare', + psk: derivePskFromHashtag(bare), + ); + } + /// True if [uri] is a valid channel share URI. (#161) static bool isValidShareUri(String uri) => fromShareUri(uri) != null; diff --git a/lib/screens/community_qr_scanner_screen.dart b/lib/screens/community_qr_scanner_screen.dart index febe4e72..a49f4931 100644 --- a/lib/screens/community_qr_scanner_screen.dart +++ b/lib/screens/community_qr_scanner_screen.dart @@ -9,6 +9,7 @@ import '../models/community.dart'; import '../storage/community_store.dart'; import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/qr_scanner_widget.dart'; +import '../helpers/channel_share_add.dart'; import '../helpers/channel_slot_ui.dart'; import '../helpers/snack_bar_builder.dart'; @@ -278,65 +279,11 @@ class _CommunityQrScannerScreenState extends State { } return; } - final connector = context.read(); - if (connector.channels.any((c) => c.pskHex == channel.pskHex)) { - if (context.mounted) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.channels_qrExists(channel.name)), - ); - Navigator.pop(context); - } - return; - } - // No slot is chosen here. It used to be, and that is the same bug the - // channels screen had: the index was picked before the confirmation - // dialog below and written after it, so a channel sync during the - // confirmation (a channel write starts one) could leave it pointing at - // an occupied slot. The slot is now chosen after the user confirms. if (!context.mounted) return; - final confirmed = await showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.channels_scanQr), - content: Text(context.l10n.channels_qrAddConfirm(channel.name)), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext, false), - child: Text(context.l10n.common_cancel), - ), - FilledButton( - onPressed: () => Navigator.pop(dialogContext, true), - child: Text(context.l10n.common_add), - ), - ], - ), - ); - if (confirmed == true && context.mounted) { - final slot = allocateChannelSlotOrExplain( - context, - connector, - psk: channel.psk, - ); - // Refused: the persistent message explains why. Stay on this screen so - // the user can retry, rather than popping away from the explanation. - if (slot == null) return; - final result = await connector.setChannel( - slot, - channel.name, - channel.psk, - ); - if (!context.mounted) return; - // Not confirmed: stay on this screen with the explanation showing. - if (explainUnconfirmedChannelWrite(context, result)) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.channels_qrAdded(channel.name)), - backgroundColor: Colors.green, - ); - Navigator.pop(context); - } else if (context.mounted) { - Navigator.pop(context); - } + final outcome = await confirmAndAddSharedChannel(context, channel); + // Refused: the persistent message explains why. Stay on this screen so + // the user can retry, rather than popping away from the explanation. + if (outcome == SharedChannelAdd.refused || !context.mounted) return; + Navigator.pop(context); } } diff --git a/lib/services/link_router.dart b/lib/services/link_router.dart new file mode 100644 index 00000000..f44f13b2 --- /dev/null +++ b/lib/services/link_router.dart @@ -0,0 +1,120 @@ +import 'package:flutter/foundation.dart'; + +import '../connector/meshcore_protocol.dart'; +import '../models/channel.dart'; +import '../models/contact.dart'; + +/// A share link Offband can act on. +sealed class ShareLink { + const ShareLink(); + + /// What the link adds, for "Connect a radio to add ...", or null when the + /// link does not say. + String? get displayName; +} + +class ChannelShareLink extends ShareLink { + const ChannelShareLink(this.channel); + final Channel channel; + + @override + String get displayName => channel.name; +} + +class ContactShareLink extends ShareLink { + const ContactShareLink(this.uri, this.contact); + + /// The link as received. The add-contact dialog parses it again itself, so + /// a link and a paste fill the dialog the same way. + final String uri; + final Contact contact; + + @override + String get displayName => contact.name; +} + +/// The older `meshcore://` form, which "Copy Advert to +/// Clipboard" still produces. The radio imports it as is, so it is carried +/// as bytes; the name is inside the signed advert and only the radio reads +/// it. +class AdvertShareLink extends ShareLink { + const AdvertShareLink(this.advert); + final Uint8List advert; + + @override + String? get displayName => null; +} + +// An advert is at least 98 bytes: key, timestamp, signature, flags. +final _advertLink = RegExp(r'^meshcore://((?:[0-9a-fA-F]{2}){98,})$'); + +/// Parses [raw] into a link Offband can add, or null if it is not one. +ShareLink? parseShareLink(String raw) { + final trimmed = raw.trim(); + final channel = Channel.fromShareUri(trimmed); + if (channel != null) return ChannelShareLink(channel); + final contact = Contact.fromShareUri(trimmed); + if (contact != null) return ContactShareLink(trimmed, contact); + final advert = _advertLink.firstMatch(trimmed); + if (advert != null) return AdvertShareLink(hex2Uint8List(advert[1]!)); + return null; +} + +/// The one place a share link goes, wherever it came from: a tap in a +/// message, the OS, the web client's address bar (#1289). +/// +/// A link is never acted on here. It is held until the app can show its +/// confirmation, and `LinkRouterHost` shows it. Only the latest link is held, +/// and only in memory: an old link must not pop up days later. +class LinkRouter extends ChangeNotifier { + ShareLink? _pending; + bool _pendingAnnounced = false; + String? _rejected; + + ShareLink? get pending => _pending; + + /// True once the user has been told the pending link is waiting for a + /// radio, so the message is shown once per link, not on every change. + bool get pendingAnnounced => _pendingAnnounced; + + /// Takes a link from any source. Returns false if it is not one Offband + /// can add; the host then tells the user so. + bool handle(String raw) { + final link = parseShareLink(raw); + if (link == null) { + _rejected = raw; + } else { + _pending = link; + _pendingAnnounced = false; + } + notifyListeners(); + return link != null; + } + + /// The pending link if its confirmation can be shown now, removing it. + /// + /// Adding anything needs a connected radio. A channel also waits for the + /// channel table to settle: right after connecting, the connector empties + /// its channel list while it syncs, so a duplicate check would miss a + /// channel the radio already has, and the slot picker would refuse. + ShareLink? takeIfReady({ + required bool connected, + required bool channelTableBusy, + }) { + final link = _pending; + if (link == null || !connected) return null; + if (link is ChannelShareLink && channelTableBusy) return null; + _pending = null; + _pendingAnnounced = false; + return link; + } + + void markPendingAnnounced() => _pendingAnnounced = true; + + /// The last link that could not be parsed, removing it. + String? takeRejected() { + final rejected = _rejected; + _rejected = null; + return rejected; + } +} diff --git a/lib/widgets/link_router_host.dart b/lib/widgets/link_router_host.dart new file mode 100644 index 00000000..de37df52 --- /dev/null +++ b/lib/widgets/link_router_host.dart @@ -0,0 +1,139 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/channel_share_add.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../services/link_router.dart'; +import 'add_contact_by_key_dialog.dart'; +import 'contact_add_feedback.dart'; + +/// Shows the confirmation for a share link held by [LinkRouter] as soon as +/// one can be shown, and says why when it cannot (#1289). +/// +/// It wraps the home route, so it sits below the Navigator and its dialogs +/// and messages open over whatever screen is on top. +class LinkRouterHost extends StatefulWidget { + const LinkRouterHost({super.key, required this.child}); + + final Widget child; + + @override + State createState() => _LinkRouterHostState(); +} + +class _LinkRouterHostState extends State { + late final LinkRouter _router; + late final MeshCoreConnector _connector; + bool _scheduled = false; + bool _showing = false; + + @override + void initState() { + super.initState(); + _router = context.read(); + _connector = context.read(); + _router.addListener(_schedule); + _connector.addListener(_schedule); + _schedule(); + } + + @override + void dispose() { + _router.removeListener(_schedule); + _connector.removeListener(_schedule); + super.dispose(); + } + + // Listeners can fire mid-build; dialogs open after the frame. + void _schedule() { + if (_scheduled) return; + _scheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _scheduled = false; + if (mounted) _check(); + }); + } + + Future _check() async { + if (_showing) return; + final l10n = context.l10n; + if (_router.takeRejected() != null) { + showDismissibleSnackBar( + context, + content: Text(l10n.link_invalid), + persist: true, + ); + } + final link = _router.takeIfReady( + connected: _connector.isConnected, + channelTableBusy: _connector.isChannelTableBusy, + ); + if (link == null) { + final waiting = _router.pending; + if (waiting != null && !_router.pendingAnnounced) { + _router.markPendingAnnounced(); + final name = waiting.displayName; + showDismissibleSnackBar( + context, + content: Text( + name == null + ? l10n.link_waitingForRadioContact + : l10n.link_waitingForRadio(name), + ), + persist: true, + ); + } + return; + } + _showing = true; + try { + switch (link) { + case ChannelShareLink(:final channel): + await confirmAndAddSharedChannel(context, channel); + case ContactShareLink(:final uri): + await showAddContactByKeyDialog(context, initialKeyText: uri); + case AdvertShareLink(:final advert): + await _importAdvert(advert); + } + } finally { + _showing = false; + } + // A link that arrived while this one was open. + if (mounted) _schedule(); + } + + /// The same import "Add Contact from Clipboard" does, after a confirmation. + Future _importAdvert(Uint8List advert) async { + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.link_addContactTitle), + content: Text(dialogContext.l10n.link_importAdvertConfirm), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(dialogContext.l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(dialogContext.l10n.common_add), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + await addContactWithFeedback( + context, + _connector, + '', + () => _connector.importContact(buildImportContactFrame(advert)), + ); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/test/helpers/meshcore_linkifier_test.dart b/test/helpers/meshcore_linkifier_test.dart new file mode 100644 index 00000000..5a6b8e4b --- /dev/null +++ b/test/helpers/meshcore_linkifier_test.dart @@ -0,0 +1,57 @@ +import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/link_handler.dart'; + +// #1289: a meshcore:// link in a message is tappable. The stock URL +// linkifier only finds http(s) and www, so before this the link was plain +// text. + +const _link = 'meshcore://channel/add?name=%23example'; + +/// The same chain, in the same order, LinkHandler gives Linkify. +List _parse(String text) { + const options = LinkifyOptions(humanize: false, defaultToHttps: false); + var elements = [TextElement(text)]; + for (final linkifier in const [ + MeshcoreLinkifier(), + UrlLinkifier(), + EmailLinkifier(), + ]) { + elements = linkifier.parse(elements, options); + } + return elements; +} + +void main() { + test('finds a meshcore:// link in a sentence', () { + final elements = _parse('join $_link now'); + final links = elements.whereType().toList(); + expect(links.map((e) => e.url), [_link]); + expect(elements.first, isA()); + expect((elements.first as TextElement).text, 'join '); + expect((elements.last as TextElement).text, ' now'); + }); + + test('leaves a full stop after the link out of it', () { + final elements = _parse('Join $_link.'); + expect(elements.whereType().single.url, _link); + expect((elements.last as TextElement).text, '.'); + }); + + test('finds several links and still finds web links', () { + final elements = _parse( + '$_link and https://offband.org and meshcore://contact/add?name=B', + ); + expect(elements.whereType().map((e) => e.url), [ + _link, + 'https://offband.org', + 'meshcore://contact/add?name=B', + ]); + }); + + test('plain text is left alone', () { + final elements = _parse('no links here'); + expect(elements, hasLength(1)); + expect((elements.single as TextElement).text, 'no links here'); + }); +} diff --git a/test/models/channel_share_uri_test.dart b/test/models/channel_share_uri_test.dart index f35fa5cd..1d43eadc 100644 --- a/test/models/channel_share_uri_test.dart +++ b/test/models/channel_share_uri_test.dart @@ -59,4 +59,35 @@ void main() { expect(Channel.isValidShareUri('not a uri at all'), isFalse); }); }); + + group('Hashtag share link without a secret (#1289)', () { + // The keys in the reference links above are the hashtag keys, so a link + // without a secret must derive exactly those. + test('derives the same key the reference app shares', () { + final echo = Channel.fromShareUri('meshcore://channel/add?name=%23echo'); + expect(echo, isNotNull); + expect(echo!.name, '#echo'); + expect(echo.pskHex, '5d25cf40b1f5b4a7eb0cf9703634a948'); + + final test = Channel.fromShareUri('meshcore://channel/add?name=%23test'); + expect(test!.pskHex, '9cd8fcf22a47333b591d96a2b848b73f'); + }); + + test('#public means the real Public channel', () { + final ch = Channel.fromShareUri('meshcore://channel/add?name=%23Public'); + expect(ch, isNotNull); + expect(ch!.name, 'Public'); + expect(ch.pskHex, Channel.publicChannelPsk); + }); + + test('a name that is not a hashtag still needs a secret', () { + expect(Channel.fromShareUri('meshcore://channel/add?name=x'), isNull); + expect(Channel.fromShareUri('meshcore://channel/add?name=%23'), isNull); + expect( + Channel.fromShareUri('meshcore://channel/add?name=%23%20'), + isNull, + ); + expect(Channel.fromShareUri('meshcore://channel/add'), isNull); + }); + }); } diff --git a/test/services/link_router_test.dart b/test/services/link_router_test.dart new file mode 100644 index 00000000..675272cd --- /dev/null +++ b/test/services/link_router_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/services/link_router.dart'; + +// #1289: every share link goes through LinkRouter, which holds it until its +// confirmation can be shown and never adds anything itself. + +const _key = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; +const _channelLink = + 'meshcore://channel/add?name=%23echo&secret=5d25cf40b1f5b4a7eb0cf9703634a948'; +const _hashtagLink = 'meshcore://channel/add?name=%23example'; +const _contactLink = 'meshcore://contact/add?name=Bob&public_key=$_key&type=1'; +final _advertLink = 'meshcore://${'ab' * 98}'; + +void main() { + group('parseShareLink', () { + test('reads every link form Offband produces or accepts', () { + expect(parseShareLink(_channelLink), isA()); + final hashtag = parseShareLink(_hashtagLink) as ChannelShareLink; + expect( + hashtag.channel.pskHex, + Channel( + index: 0, + name: '#example', + psk: Channel.derivePskFromHashtag('example'), + ).pskHex, + ); + final contact = parseShareLink(_contactLink) as ContactShareLink; + expect(contact.contact.name, 'Bob'); + expect(contact.uri, _contactLink); + final advert = parseShareLink(_advertLink) as AdvertShareLink; + expect(advert.advert.length, 98); + }); + + test('tolerates surrounding whitespace', () { + expect(parseShareLink(' $_channelLink\n'), isA()); + }); + + test('rejects anything else', () { + for (final bad in [ + 'https://example.com', + 'meshcore://channel/add?name=x', + 'meshcore://contact/add?name=Bob', + 'meshcore://${'ab' * 10}', + 'meshcore://${'ab' * 98}a', + 'meshcore://zz', + '', + ]) { + expect(parseShareLink(bad), isNull, reason: bad); + } + }); + }); + + group('LinkRouter', () { + test('a malformed link is reported, not dropped', () { + final router = LinkRouter(); + var notified = 0; + router.addListener(() => notified++); + expect(router.handle('meshcore://nope'), isFalse); + expect(notified, 1); + expect(router.pending, isNull); + expect(router.takeRejected(), 'meshcore://nope'); + expect(router.takeRejected(), isNull); + }); + + test('a link is held while no radio is connected', () { + final router = LinkRouter()..handle(_channelLink); + expect( + router.takeIfReady(connected: false, channelTableBusy: false), + isNull, + ); + expect(router.pending, isA()); + final link = router.takeIfReady(connected: true, channelTableBusy: false); + expect(link, isA()); + expect(router.pending, isNull); + }); + + test('a channel link waits for the channel table to settle', () { + final router = LinkRouter()..handle(_channelLink); + expect( + router.takeIfReady(connected: true, channelTableBusy: true), + isNull, + ); + expect(router.pending, isNotNull); + }); + + test('a contact link does not wait for the channel table', () { + final router = LinkRouter()..handle(_contactLink); + expect( + router.takeIfReady(connected: true, channelTableBusy: true), + isA(), + ); + }); + + test('only the latest link is held, and it is announced afresh', () { + final router = LinkRouter()..handle(_channelLink); + router.markPendingAnnounced(); + expect(router.pendingAnnounced, isTrue); + router.handle(_contactLink); + expect(router.pending, isA()); + expect(router.pendingAnnounced, isFalse); + }); + + test('a malformed link does not replace a held one', () { + final router = LinkRouter()..handle(_channelLink); + router.handle('meshcore://nope'); + expect(router.pending, isA()); + }); + }); +} diff --git a/test/widgets/link_router_host_test.dart b/test/widgets/link_router_host_test.dart new file mode 100644 index 00000000..1ccc4cc1 --- /dev/null +++ b/test/widgets/link_router_host_test.dart @@ -0,0 +1,163 @@ +// #1289: a share link opens the existing confirmation, waits for a radio +// when none is connected, and never adds anything the user did not confirm. + +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/helpers/link_handler.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/services/link_router.dart'; +import 'package:meshcore_open/widgets/link_router_host.dart'; + +const _link = 'meshcore://channel/add?name=%23example'; + +class _Radio extends MeshCoreConnector { + bool connected = false; + bool busy = false; + final List onRadio = []; + final List<(int, String, String)> writes = []; + + void change() => notifyListeners(); + + @override + bool get isConnected => connected; + @override + bool get isChannelTableBusy => busy; + @override + List get channels => List.unmodifiable(onRadio); + @override + int get maxChannels => 8; + @override + Future setChannel( + int index, + String name, + Uint8List psk, { + bool refresh = true, + }) async { + writes.add(( + index, + name, + Channel(index: index, name: name, psk: psk).pskHex, + )); + return ChannelWrite.ok; + } +} + +Future<(LinkRouter, BuildContext)> _pump( + WidgetTester tester, + _Radio radio, +) async { + final router = LinkRouter(); + late BuildContext inner; + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: radio), + ChangeNotifierProvider.value(value: router), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: LinkRouterHost( + child: Scaffold( + body: Builder( + builder: (context) { + inner = context; + return const SizedBox.expand(); + }, + ), + ), + ), + ), + ), + ); + return (router, inner); +} + +void main() { + testWidgets('waits for a radio, then confirms, then writes', (tester) async { + final radio = _Radio(); + final (router, _) = await _pump(tester, radio); + + router.handle(_link); + await tester.pumpAndSettle(); + expect(find.textContaining('Connect a radio to add #example'), findsOne); + expect(find.byType(AlertDialog), findsNothing); + + radio + ..connected = true + ..busy = true + ..change(); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing, reason: 'table busy'); + + radio + ..busy = false + ..change(); + await tester.pumpAndSettle(); + expect(find.text('Add channel "#example"?'), findsOne); + expect(radio.writes, isEmpty, reason: 'nothing before confirming'); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + expect(radio.writes, hasLength(1)); + expect(radio.writes.single.$2, '#example'); + expect( + radio.writes.single.$3, + Channel( + index: 0, + name: '#example', + psk: Channel.derivePskFromHashtag('example'), + ).pskHex, + ); + }); + + testWidgets('cancel writes nothing', (tester) async { + final radio = _Radio()..connected = true; + final (router, _) = await _pump(tester, radio); + router.handle(_link); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); + await tester.pumpAndSettle(); + expect(radio.writes, isEmpty); + expect(router.pending, isNull); + }); + + testWidgets('a channel already on the radio is not offered again', ( + tester, + ) async { + final radio = _Radio()..connected = true; + radio.onRadio.add(Channel.fromShareUri(_link, index: 1)!); + final (router, _) = await _pump(tester, radio); + router.handle(_link); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text('"#example" is already added.'), findsOne); + expect(radio.writes, isEmpty); + }); + + testWidgets('a malformed link says so', (tester) async { + final radio = _Radio()..connected = true; + final (router, _) = await _pump(tester, radio); + router.handle('meshcore://channel/add?name=nope'); + await tester.pumpAndSettle(); + expect(find.textContaining("isn't a channel or contact"), findsOne); + }); + + testWidgets('tapping a meshcore:// link in a message routes it here', ( + tester, + ) async { + final radio = _Radio()..connected = true; + final (_, inner) = await _pump(tester, radio); + LinkHandler.handleLinkTap(inner, _link); + await tester.pumpAndSettle(); + // Offband's own confirmation, not the browser's "Open Link" dialog. + expect(find.text('Add channel "#example"?'), findsOne); + expect(find.text('Open Link'), findsNothing); + }); +} diff --git a/untranslated.json b/untranslated.json index 782589fc..21ca628d 100644 --- a/untranslated.json +++ b/untranslated.json @@ -465,7 +465,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "de": [ @@ -934,7 +939,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "es": [ @@ -1403,7 +1413,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "fr": [ @@ -1872,7 +1887,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "hu": [ @@ -2341,7 +2361,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "it": [ @@ -2810,7 +2835,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "ja": [ @@ -3279,7 +3309,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "ko": [ @@ -3748,7 +3783,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "nl": [ @@ -4217,7 +4257,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "pl": [ @@ -4686,7 +4731,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "pt": [ @@ -5155,7 +5205,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "ru": [ @@ -5624,7 +5679,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "sk": [ @@ -6093,7 +6153,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "sl": [ @@ -6562,7 +6627,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "sv": [ @@ -7031,7 +7101,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "uk": [ @@ -7500,7 +7575,12 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ], "zh": [ @@ -7969,6 +8049,11 @@ "storage_confirmIrreversible", "storage_confirmKeptBack", "storage_confirmAction", - "storage_resultFailed" + "storage_resultFailed", + "link_invalid", + "link_waitingForRadio", + "link_waitingForRadioContact", + "link_addContactTitle", + "link_importAdvertConfirm" ] } From 16a1e62f57dad93ef12ee6538fa3892a38888967 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:58:12 -0500 Subject: [PATCH 2/3] feat(#1291): open meshcore:// links in Offband on Android, iOS and macOS No platform declared the meshcore scheme, so a share link tapped in a browser or another app went nowhere. - Android: a meshcore VIEW/BROWSABLE intent filter on MainActivity, and flutter_deeplinking_enabled=false, which app_links needs; otherwise Flutter treats "channel/add" as a screen to navigate to. - iOS: CFBundleURLTypes for meshcore, and FlutterDeepLinkingEnabled=false. - macOS: CFBundleURLTypes for meshcore. - app_links 7.2.2 (Apache-2.0) feeds the link the app was opened with, and later ones, to LinkRouter (#1289). Only meshcore:// links are acted on: on web the page's own address arrives as the initial link, and an ordinary launch must not show a link message. Windows and Linux wait on how the app is installed (#1284). Regression tests: - share_link_registration_test: the three platform declarations. All three fail against dev's manifest and plists. - link_router_test: only share links are taken from the OS. - link_router_host_test: a link from the OS opens the confirmation, and an ordinary address does nothing. Epic: #1286 Feature: #1280 Agent: StormyElk (session 088ce922) --- android/app/src/main/AndroidManifest.xml | 10 ++++ ios/Runner/Info.plist | 13 ++++ lib/main.dart | 6 +- lib/services/link_router.dart | 9 +++ lib/widgets/link_router_host.dart | 16 ++++- linux/flutter/generated_plugin_registrant.cc | 4 ++ linux/flutter/generated_plugins.cmake | 1 + macos/Flutter/GeneratedPluginRegistrant.swift | 2 + macos/Runner/Info.plist | 11 ++++ pubspec.lock | 32 ++++++++++ pubspec.yaml | 1 + .../share_link_registration_test.dart | 59 +++++++++++++++++++ test/services/link_router_test.dart | 15 +++++ test/widgets/link_router_host_test.dart | 30 ++++++++++ .../flutter/generated_plugin_registrant.cc | 3 + windows/flutter/generated_plugins.cmake | 1 + 16 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 test/platform/share_link_registration_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index cf7472db..efbf7ed6 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -51,6 +51,16 @@ + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 0088b76d..2c299446 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -22,8 +22,21 @@ $(FLUTTER_BUILD_NAME) CFBundleSignature ???? + CFBundleURLTypes + + + CFBundleURLName + app.offband.meshcore.share + CFBundleURLSchemes + + meshcore + + + CFBundleVersion $(FLUTTER_BUILD_NUMBER) + FlutterDeepLinkingEnabled + ITSAppUsesNonExemptEncryption LSApplicationQueriesSchemes diff --git a/lib/main.dart b/lib/main.dart index e806f7f1..c1beed97 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:app_links/app_links.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter/foundation.dart'; @@ -442,8 +443,9 @@ class MeshCoreApp extends StatelessWidget { }, home: (PlatformInfo.isWeb && !PlatformInfo.isChrome) ? const ChromeRequiredScreen() - : const LinkRouterHost( - child: IosOnMacNoticeGate( + : LinkRouterHost( + osLinks: AppLinks().uriLinkStream, + child: const IosOnMacNoticeGate( child: SponsorPromptGate(child: ScannerScreen()), ), ), diff --git a/lib/services/link_router.dart b/lib/services/link_router.dart index f44f13b2..466f50c8 100644 --- a/lib/services/link_router.dart +++ b/lib/services/link_router.dart @@ -91,6 +91,15 @@ class LinkRouter extends ChangeNotifier { return link != null; } + /// Takes a link the OS opened the app with (#1291). Only share links are + /// acted on: the OS also reports ordinary launches, and on web the page's + /// own address arrives as the "initial link", neither of which is the + /// user asking to add anything, so they are ignored rather than reported. + void handleFromOs(Uri uri) { + if (uri.scheme.toLowerCase() != 'meshcore') return; + handle(uri.toString()); + } + /// The pending link if its confirmation can be shown now, removing it. /// /// Adding anything needs a connected radio. A channel also waits for the diff --git a/lib/widgets/link_router_host.dart b/lib/widgets/link_router_host.dart index de37df52..282ea65c 100644 --- a/lib/widgets/link_router_host.dart +++ b/lib/widgets/link_router_host.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -8,6 +10,7 @@ import '../helpers/channel_share_add.dart'; import '../helpers/snack_bar_builder.dart'; import '../l10n/l10n.dart'; import '../services/link_router.dart'; +import '../utils/app_logger.dart'; import 'add_contact_by_key_dialog.dart'; import 'contact_add_feedback.dart'; @@ -17,10 +20,14 @@ import 'contact_add_feedback.dart'; /// It wraps the home route, so it sits below the Navigator and its dialogs /// and messages open over whatever screen is on top. class LinkRouterHost extends StatefulWidget { - const LinkRouterHost({super.key, required this.child}); + const LinkRouterHost({super.key, required this.child, this.osLinks}); final Widget child; + /// Links the OS opened the app with: the one that launched it, then any + /// that arrive while it runs (#1291). Null in tests that do not need it. + final Stream? osLinks; + @override State createState() => _LinkRouterHostState(); } @@ -28,6 +35,7 @@ class LinkRouterHost extends StatefulWidget { class _LinkRouterHostState extends State { late final LinkRouter _router; late final MeshCoreConnector _connector; + StreamSubscription? _osLinks; bool _scheduled = false; bool _showing = false; @@ -38,11 +46,17 @@ class _LinkRouterHostState extends State { _connector = context.read(); _router.addListener(_schedule); _connector.addListener(_schedule); + _osLinks = widget.osLinks?.listen( + _router.handleFromOs, + onError: (Object e) => + appLogger.warn('OS link stream error: $e', tag: 'LinkRouter'), + ); _schedule(); } @override void dispose() { + _osLinks?.cancel(); _router.removeListener(_schedule); _connector.removeListener(_schedule); super.dispose(); diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index 6cf6d508..8b17840d 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,12 +6,16 @@ #include "generated_plugin_registrant.h" +#include #include #include #include #include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) app_links_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AppLinksPluginLinux"); + app_links_plugin_linux_register_with_registrar(app_links_linux_registrar); g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); file_selector_plugin_register_with_registrar(file_selector_linux_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index b86d669d..ce25e14c 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + app_links_linux file_selector_linux screen_retriever_linux url_launcher_linux diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 6a868e65..d48ef348 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,7 @@ import FlutterMacOS import Foundation +import app_links import file_selector_macos import flutter_blue_plus_darwin import flutter_local_notifications @@ -20,6 +21,7 @@ import wakelock_plus import window_manager func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin")) FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist index c55e9d73..8e24db1d 100644 --- a/macos/Runner/Info.plist +++ b/macos/Runner/Info.plist @@ -18,6 +18,17 @@ APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) + CFBundleURLTypes + + + CFBundleURLName + app.offband.meshcore.share + CFBundleURLSchemes + + meshcore + + + CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSMinimumSystemVersion diff --git a/pubspec.lock b/pubspec.lock index d0c8005c..058abef0 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -25,6 +25,38 @@ packages: url: "https://pub.dev" source: hosted version: "12.1.0" + app_links: + dependency: "direct main" + description: + name: app_links + sha256: "08ba88bf19d9edea33130cb71c8ced2cb982b4e00b82efef4a434d1357bc69c3" + url: "https://pub.dev" + source: hosted + version: "7.2.2" + app_links_linux: + dependency: transitive + description: + name: app_links_linux + sha256: "734aa57a2f65d1b35c3643384ccfbe668730157a08479bfa488e10a9da847853" + url: "https://pub.dev" + source: hosted + version: "1.0.5" + app_links_platform_interface: + dependency: transitive + description: + name: app_links_platform_interface + sha256: "7546f09a6e93f4a2df2fe2bd40a5c6c64310ac461b036d82b43033be7a59f809" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + app_links_web: + dependency: transitive + description: + name: app_links_web + sha256: "382d32c6f486f15b1d7f5d6a37a70a481a4fc08382eef419d373169921a3e765" + url: "https://pub.dev" + source: hosted + version: "1.0.5" archive: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 1cb112ad..a13492f3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -62,6 +62,7 @@ dependencies: qr_flutter: ^4.1.0 # QR code generation url_launcher: ^6.3.0 # Launch URLs in system browser flutter_linkify: ^6.0.0 # Auto-detect and linkify URLs in text + app_links: ^7.2.2 # meshcore:// and offband.app share links from the OS (#1280) gpx: ^2.3.0 yaml: ^3.1.2 # Parse importable device config profiles (#403) path_provider: ^2.1.6 diff --git a/test/platform/share_link_registration_test.dart b/test/platform/share_link_registration_test.dart new file mode 100644 index 00000000..85a73836 --- /dev/null +++ b/test/platform/share_link_registration_test.dart @@ -0,0 +1,59 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +// #1291: the OS only hands a meshcore:// link to Offband if the app declares +// the scheme. Before this, none of the platforms did, so a tapped link went +// nowhere. Flutter's own deep-link routing must also be off where app_links +// needs it, or Flutter treats "channel/add" as a screen to navigate to. + +String _read(String path) => File(path).readAsStringSync(); + +/// The `` blocks in the Android manifest. +Iterable _intentFilters(String manifest) => RegExp( + r'([\s\S]*?)', +).allMatches(manifest).map((m) => m[1]!); + +/// True if a `CFBundleURLSchemes` array in [plist] lists [scheme]. +bool _plistDeclaresScheme(String plist, String scheme) => RegExp( + r'CFBundleURLSchemes\s*[\s\S]*?' + + RegExp.escape(scheme) + + r'[\s\S]*?', +).hasMatch(plist); + +void main() { + test('Android opens meshcore:// links in Offband', () { + final manifest = _read('android/app/src/main/AndroidManifest.xml'); + final filter = _intentFilters( + manifest, + ).where((f) => f.contains('android:scheme="meshcore"')); + expect(filter, hasLength(1), reason: 'one meshcore intent filter'); + expect(filter.single, contains('android.intent.action.VIEW')); + expect(filter.single, contains('android.intent.category.BROWSABLE')); + expect(filter.single, contains('android.intent.category.DEFAULT')); + expect( + manifest, + matches( + RegExp( + r'android:name="flutter_deeplinking_enabled"\s+android:value="false"', + ), + ), + ); + }); + + test('iOS opens meshcore:// links in Offband', () { + final plist = _read('ios/Runner/Info.plist'); + expect(_plistDeclaresScheme(plist, 'meshcore'), isTrue); + expect( + plist, + matches(RegExp(r'FlutterDeepLinkingEnabled\s*')), + ); + }); + + test('macOS opens meshcore:// links in Offband', () { + expect( + _plistDeclaresScheme(_read('macos/Runner/Info.plist'), 'meshcore'), + isTrue, + ); + }); +} diff --git a/test/services/link_router_test.dart b/test/services/link_router_test.dart index 675272cd..1f9edf80 100644 --- a/test/services/link_router_test.dart +++ b/test/services/link_router_test.dart @@ -101,6 +101,21 @@ void main() { expect(router.pendingAnnounced, isFalse); }); + test('from the OS, only share links are acted on (#1291)', () { + final router = LinkRouter(); + // An ordinary launch, and on web the page's own address. + router.handleFromOs(Uri.parse('https://offband.app/')); + router.handleFromOs(Uri.parse('offband://open')); + expect(router.pending, isNull); + expect(router.takeRejected(), isNull, reason: 'not reported either'); + + router.handleFromOs(Uri.parse(_hashtagLink)); + expect(router.pending, isA()); + + router.handleFromOs(Uri.parse('MESHCORE://channel/add?name=nope')); + expect(router.takeRejected(), isNotNull, reason: 'a broken share link'); + }); + test('a malformed link does not replace a held one', () { final router = LinkRouter()..handle(_channelLink); router.handle('meshcore://nope'); diff --git a/test/widgets/link_router_host_test.dart b/test/widgets/link_router_host_test.dart index 1ccc4cc1..87979712 100644 --- a/test/widgets/link_router_host_test.dart +++ b/test/widgets/link_router_host_test.dart @@ -1,6 +1,7 @@ // #1289: a share link opens the existing confirmation, waits for a radio // when none is connected, and never adds anything the user did not confirm. +import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/material.dart'; @@ -149,6 +150,35 @@ void main() { expect(find.textContaining("isn't a channel or contact"), findsOne); }); + testWidgets('a link from the OS opens the confirmation (#1291)', ( + tester, + ) async { + final radio = _Radio()..connected = true; + final os = StreamController(); + addTearDown(os.close); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: radio), + ChangeNotifierProvider(create: (_) => LinkRouter()), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: LinkRouterHost(osLinks: os.stream, child: const Scaffold()), + ), + ), + ); + os.add(Uri.parse('https://offband.app/')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.textContaining("isn't a channel"), findsNothing); + + os.add(Uri.parse(_link)); + await tester.pumpAndSettle(); + expect(find.text('Add channel "#example"?'), findsOne); + }); + testWidgets('tapping a meshcore:// link in a message routes it here', ( tester, ) async { diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 58ed7ef3..7382e393 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,7 @@ #include "generated_plugin_registrant.h" +#include #include #include #include @@ -14,6 +15,8 @@ #include void RegisterPlugins(flutter::PluginRegistry* registry) { + AppLinksPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AppLinksPluginCApi")); FileSelectorWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("FileSelectorWindows")); FlutterBluePlusPluginRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index e615315f..1fec65fc 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + app_links file_selector_windows flutter_blue_plus_winrt screen_retriever_windows From 22815ee4042dbd623366040d24e5d6a4d8b84c50 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:20:48 -0500 Subject: [PATCH 3/3] fix(#1289): tighten share-link parsing from review Three gaps found in review: - A link in brackets, "(meshcore://...)", took the closing bracket with it and was reported as invalid. The bracket is now left out unless the link opened one itself. - The legacy advert form had no upper length, so a huge link from another app was decoded in full. An advert fits in one radio packet, so anything past 255 bytes is refused. - A channel link with a blank name and a secret was accepted, and would add a channel with no visible name. It is refused. Regression tests, each failing against the code before this commit: - meshcore_linkifier_test: a closing bracket is left out of the link. - link_router_test: a 256-byte advert link is refused. - channel_share_uri_test: a blank name is refused even with a secret. Epic: #1285 Feature: #1280 Agent: StormyElk (session 088ce922) --- lib/helpers/link_handler.dart | 9 ++++++++- lib/models/channel.dart | 2 +- lib/services/link_router.dart | 5 +++-- test/helpers/meshcore_linkifier_test.dart | 11 +++++++++++ test/models/channel_share_uri_test.dart | 10 ++++++++++ test/services/link_router_test.dart | 2 ++ 6 files changed, 35 insertions(+), 4 deletions(-) diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index f4f6e9a1..6a5a5556 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -30,7 +30,14 @@ class MeshcoreLinkifier extends Linkifier { var last = 0; for (final match in _link.allMatches(text)) { // A sentence ending right after a link keeps its full stop. - final url = match[0]!.replaceFirst(_trailingPunctuation, ''); + var url = match[0]!.replaceFirst(_trailingPunctuation, ''); + // "(meshcore://...)": the closing bracket is the sentence's, unless + // the link opened one itself. + if (url.endsWith(')') && !url.contains('(')) { + url = url + .substring(0, url.length - 1) + .replaceFirst(_trailingPunctuation, ''); + } final end = match.start + url.length; if (match.start > last) { out.add(TextElement(text.substring(last, match.start))); diff --git a/lib/models/channel.dart b/lib/models/channel.dart index 1d784264..7d00cfea 100644 --- a/lib/models/channel.dart +++ b/lib/models/channel.dart @@ -125,7 +125,7 @@ class Channel { if (parsed.path.replaceAll('/', '') != 'add') return null; final name = parsed.queryParameters['name']; final secret = parsed.queryParameters['secret']; - if (name == null) return null; + if (name == null || name.trim().isEmpty) return null; if (secret == null) return _fromHashtagName(name, index); try { return Channel(index: index, name: name, psk: parsePskHex(secret)); diff --git a/lib/services/link_router.dart b/lib/services/link_router.dart index 466f50c8..3a392e23 100644 --- a/lib/services/link_router.dart +++ b/lib/services/link_router.dart @@ -45,8 +45,9 @@ class AdvertShareLink extends ShareLink { String? get displayName => null; } -// An advert is at least 98 bytes: key, timestamp, signature, flags. -final _advertLink = RegExp(r'^meshcore://((?:[0-9a-fA-F]{2}){98,})$'); +// An advert is at least 98 bytes: key, timestamp, signature, flags. It fits +// in one radio packet, so anything past 255 bytes is not one. +final _advertLink = RegExp(r'^meshcore://((?:[0-9a-fA-F]{2}){98,255})$'); /// Parses [raw] into a link Offband can add, or null if it is not one. ShareLink? parseShareLink(String raw) { diff --git a/test/helpers/meshcore_linkifier_test.dart b/test/helpers/meshcore_linkifier_test.dart index 5a6b8e4b..bd9d114d 100644 --- a/test/helpers/meshcore_linkifier_test.dart +++ b/test/helpers/meshcore_linkifier_test.dart @@ -49,6 +49,17 @@ void main() { ]); }); + test('leaves a closing bracket around the link out of it', () { + final elements = _parse('(see $_link).'); + expect(elements.whereType().single.url, _link); + expect((elements.last as TextElement).text, ').'); + }); + + test('keeps a bracket the link itself opened', () { + const named = 'meshcore://channel/add?name=%23a(b)'; + expect(_parse('join $named').whereType().single.url, named); + }); + test('plain text is left alone', () { final elements = _parse('no links here'); expect(elements, hasLength(1)); diff --git a/test/models/channel_share_uri_test.dart b/test/models/channel_share_uri_test.dart index 1d43eadc..467f6354 100644 --- a/test/models/channel_share_uri_test.dart +++ b/test/models/channel_share_uri_test.dart @@ -89,5 +89,15 @@ void main() { ); expect(Channel.fromShareUri('meshcore://channel/add'), isNull); }); + + test('a blank name is refused, even with a secret', () { + expect( + Channel.fromShareUri( + 'meshcore://channel/add?name=%20%20' + '&secret=00112233445566778899aabbccddeeff', + ), + isNull, + ); + }); }); } diff --git a/test/services/link_router_test.dart b/test/services/link_router_test.dart index 1f9edf80..6b9f655a 100644 --- a/test/services/link_router_test.dart +++ b/test/services/link_router_test.dart @@ -43,6 +43,8 @@ void main() { 'meshcore://contact/add?name=Bob', 'meshcore://${'ab' * 10}', 'meshcore://${'ab' * 98}a', + // Longer than any radio packet: not an advert. + 'meshcore://${'ab' * 256}', 'meshcore://zz', '', ]) {