Configure the connect screen's node banner from a DNS TXT record

The "get a node" banner's link, and optionally its title, body and button
text, now come from the _banner.meshcoreopen.org TXT record, looked up
over Cloudflare DNS-over-HTTPS and cached for the record's TTL (1 min to
6 h). The record is `v=1;on=1;url=<https link>` with URL-encoded values;
`on=0`, a missing record or any lookup failure hides the banner.
This commit is contained in:
zjs81 committed 2026-10-24 21:29:08 -07:00
1 parent ae2db54a24
commit ee382f9177
4 files changed
+321 -16

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../storage/prefs_manager.dart';
/// DNS name whose TXT record configures the connect screen's "get a node"
/// banner, e.g. `v=1;on=1;url=https%3A%2F%2F...;title=...`.
const String nodeBannerRecordName = '_banner.meshcoreopen.org';
const String _dohEndpoint = 'https://cloudflare-dns.com/dns-query';
const String _cacheRecordKey = 'node_banner_txt';
const String _cacheExpiryKey = 'node_banner_expires_ms';
const int _dnsTypeTxt = 16;
/// Banner content from the TXT record. Null text fields fall back to the
/// app's localized strings.
class NodeBannerConfig {
final Uri url;
final String? title;
final String? body;
final String? action;
const NodeBannerConfig({
required this.url,
this.title,
this.body,
this.action,
});
/// Parses `key=value` pairs separated by `;` with URL-encoded values.
/// Returns null when the banner is switched off (`on=0`), the version is
/// unknown, or the link is missing or not https.
static NodeBannerConfig? parse(String record) {
final fields = <String, String>{};
for (final pair in record.split(';')) {
final eq = pair.indexOf('=');
if (eq <= 0) continue;
try {
fields[pair.substring(0, eq).trim().toLowerCase()] =
Uri.decodeComponent(pair.substring(eq + 1).trim());
} on ArgumentError {
return null;
}
}
if (fields['v'] != '1' || fields['on'] != '1') return null;
final url = Uri.tryParse(fields['url'] ?? '');
if (url == null || url.scheme != 'https' || url.host.isEmpty) return null;
String? text(String key) {
final value = fields[key]?.trim();
return value == null || value.isEmpty ? null : value;
}
return NodeBannerConfig(
url: url,
title: text('title'),
body: text('body'),
action: text('cta'),
);
}
}
/// Looks up the banner's TXT record over DNS-over-HTTPS and caches it for
/// the record's TTL. Any failure means no banner.
class NodeBannerService {
final http.Client _client;
final DateTime Function() _now;
NodeBannerService({http.Client? client, DateTime Function()? now})
: _client = client ?? http.Client(),
_now = now ?? DateTime.now;
Future<NodeBannerConfig?> load() async {
try {
final prefs = PrefsManager.instance;
final expires = prefs.getInt(_cacheExpiryKey) ?? 0;
final cached = prefs.getString(_cacheRecordKey);
if (cached != null && _now().millisecondsSinceEpoch < expires) {
return NodeBannerConfig.parse(cached);
}
final response = await _client
.get(
Uri.parse(_dohEndpoint).replace(
queryParameters: {'name': nodeBannerRecordName, 'type': 'TXT'},
),
headers: const {'accept': 'application/dns-json'},
)
.timeout(const Duration(seconds: 5));
if (response.statusCode != 200) return null;
final answer = txtFromDohJson(response.body);
if (answer == null) return null;
final ttl = answer.ttl.clamp(60, 6 * 3600);
await prefs.setString(_cacheRecordKey, answer.text);
await prefs.setInt(
_cacheExpiryKey,
_now().add(Duration(seconds: ttl)).millisecondsSinceEpoch,
);
return NodeBannerConfig.parse(answer.text);
} catch (e) {
debugPrint('Node banner lookup failed: $e');
return null;
}
}
/// The first TXT answer in a DoH JSON response, with its character-strings
/// joined, or null when the name has no TXT record.
@visibleForTesting
static ({String text, int ttl})? txtFromDohJson(String body) {
final json = jsonDecode(body) as Map<String, dynamic>;
if (json['Status'] != 0) return null;
for (final answer in (json['Answer'] as List<dynamic>? ?? const [])) {
final record = answer as Map<String, dynamic>;
if (record['type'] != _dnsTypeTxt) continue;
return (
text: _joinCharacterStrings(record['data'] as String),
ttl: (record['TTL'] as num?)?.toInt() ?? 300,
);
}
return null;
}
/// Joins the quoted character-strings of TXT presentation data
/// (`"a" "b"` -> `ab`), undoing `\"`, `\\` and `\DDD` escapes.
static String _joinCharacterStrings(String data) {
if (!data.contains('"')) return data;
final out = StringBuffer();
var inQuotes = false;
for (var i = 0; i < data.length; i++) {
final c = data[i];
if (c == '"') {
inQuotes = !inQuotes;
} else if (!inQuotes) {
continue;
} else if (c == r'\' && i + 1 < data.length) {
final digits = i + 3 < data.length ? data.substring(i + 1, i + 4) : '';
final code = int.tryParse(digits);
if (digits.length == 3 && code != null) {
out.writeCharCode(code);
i += 3;
} else {
out.write(data[++i]);
}
} else {
out.write(c);
}
}
return out.toString();
}
}
+31 -14
View File
@@ -2,25 +2,42 @@ import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../l10n/l10n.dart';
import '../services/node_banner_service.dart';
import '../theme/mesh_theme.dart';
/// Affiliate link for the SenseCAP MeshTracker X1.
const getNodeUrl =
'https://www.seeedstudio.com/sensecap-meshtracker-x1-meshtastic-gps-tracker-p-6935.html'
'?sensecap_affiliate=JFWID0g&referring_service=link';
/// Bottom banner on the connect screen pointing new users at a node to buy.
class GetNodeBanner extends StatelessWidget {
const GetNodeBanner({super.key});
/// Its link (and optionally its text) comes from the `_banner` DNS TXT
/// record; it stays hidden until that loads, and when the lookup fails or the
/// record turns it off.
class GetNodeBanner extends StatefulWidget {
final Future<NodeBannerConfig?> Function()? loadConfig;
void _open() =>
launchUrl(Uri.parse(getNodeUrl), mode: LaunchMode.externalApplication);
const GetNodeBanner({super.key, this.loadConfig});
@override
State<GetNodeBanner> createState() => _GetNodeBannerState();
}
class _GetNodeBannerState extends State<GetNodeBanner> {
NodeBannerConfig? _config;
@override
void initState() {
super.initState();
(widget.loadConfig ?? NodeBannerService().load)().then((config) {
if (mounted && config != null) setState(() => _config = config);
});
}
@override
Widget build(BuildContext context) {
final config = _config;
if (config == null) return const SizedBox.shrink();
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final textTheme = Theme.of(context).textTheme;
void open() => launchUrl(config.url, mode: LaunchMode.externalApplication);
return SafeArea(
top: false,
@@ -34,7 +51,7 @@ class GetNodeBanner extends StatelessWidget {
),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _open,
onTap: open,
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
child: Column(
@@ -51,7 +68,7 @@ class GetNodeBanner extends StatelessWidget {
const SizedBox(width: 10),
Expanded(
child: Text(
l10n.scanner_getNodeTitle,
config.title ?? l10n.scanner_getNodeTitle,
style: textTheme.titleMedium?.copyWith(
color: scheme.onPrimaryContainer,
fontWeight: FontWeight.w700,
@@ -62,7 +79,7 @@ class GetNodeBanner extends StatelessWidget {
),
const SizedBox(height: 6),
Text(
l10n.scanner_getNodeBody,
config.body ?? l10n.scanner_getNodeBody,
style: textTheme.bodyMedium?.copyWith(
color: scheme.onPrimaryContainer,
height: 1.35,
@@ -72,9 +89,9 @@ class GetNodeBanner extends StatelessWidget {
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: _open,
onPressed: open,
icon: const Icon(Icons.shopping_cart_outlined, size: 22),
label: Text(l10n.scanner_getNodeAction),
label: Text(config.action ?? l10n.scanner_getNodeAction),
),
),
const SizedBox(height: 6),