feat(ios/macos): detect the Local Network permission instead of failing silently

Denial of Apple's Local Network privacy permission is the most common cause of
"BikeControl can't see my trainer app" on iOS and macOS, and it fails
completely silently: Bonjour browses return nothing forever, advertisements
never leave the device, nothing throws. An app watching only for errors cannot
tell "permission is off" from "there is nothing out there".

Apple ships no authorization-status API for it (not iOS 14...26, not macOS
15...26), so the new local_network_permission plugin measures it: an NWListener
and an NWBrowser on _bikecontrol-preflight._tcp, then

  browser discovers the listener        -> granted
  kDNSServiceErr_PolicyDenied (-65570)  -> denied
  neither, before the deadline          -> unknown

unknown is a real outcome, not an error — a device with no usable network never
completes the round trip even when the permission is fine — so everything fails
open on it and only a positive denial blocks the user.

The probe *is* the request: the system prompt fires on the first Bonjour
operation, so there is no separate request step, and after the user answers,
System Settings is the only way back.

- LocalNetworkAccess caches the result (probes cost a real round trip while
  getStatus() runs on every tile mount, tap and resume) and collapses
  concurrent probes into one, since two listeners on the same service type
  would resolve each other.
- LocalNetworkRequirement gates the three LAN tiles: MyWhoosh Link, Zwift mDNS
  and OpenBikeControl mDNS. Suppressed in screenshot/demo mode like the rest.
- Diagnostics drop the old guess (inferred from whether a discovery scan
  returned anything, which could not tell denied from an empty LAN) for the
  measured local-network=granted|denied|unknown.
- _bikecontrol-preflight._tcp added to NSBonjourServices on both platforms;
  without it the browse fails for a reason unrelated to the permission.

The Xcode project deployment-target bumps (ios 13.0->15.0, macos 10.15->12.0)
are Flutter's own migration aligning project defaults with the Podfiles; they
happen on any first build.

Verified with real builds on both platforms, not just analysis: flutter build
macos --debug and flutter build ios --no-codesign both succeed, the framework
is linked in, and the preflight service type is present in both built
Info.plists. 35 tests cover the mapping, cache, concurrency and fail-open
behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jonas Bark
2026-08-21 07:58:18 +02:00
parent 8a2d83139b
commit 905c2641cd
30 changed files with 1098 additions and 47 deletions

View File

@@ -1,3 +1,7 @@
### 6.5.0 (unreleased)
**Fixes**:
- iOS & macOS: BikeControl now detects when the system "Local Network" permission is off and says so, instead of leaving the network connection methods (MyWhoosh Link, Zwift and OpenBikeControl over Wi-Fi) silently unable to find anything. Tapping the warning opens the right settings page.
### 6.4.0 (10-08-2026)
**Features**:
- Added a guided setup on first launch

View File

@@ -16,6 +16,10 @@ Here's a video with a few explanations. Note that it uses an older version, but
This is a network/local-discovery problem. BikeControl needs the same kind of local network access as MyWhoosh Link.
Checklist:
- **iOS / macOS: check the Local Network permission first.** Without it every Link connection fails silently — nothing is logged, the app just never appears.
- iOS: Settings → BikeControl → Local Network
- macOS: System Settings → Privacy & Security → Local Network
- BikeControl checks this itself and offers to open the right page, but the toggle can be revoked later (and on macOS it is sometimes lost across a reboot).
- Use the MyWhoosh Link app to confirm if "Link" works in general
- Use MyWhoosh Link app and connect, then close it, then open up BikeControl - this is key for some users
- Both devices (if you use BikeControl on another device than MyWhoosh) are on the **same Wi‑Fi SSID**

View File

@@ -8,6 +8,9 @@ PODS:
- Flutter
- gamepads_ios (0.1.1):
- Flutter
- local_network_permission (1.0.0):
- Flutter
- FlutterMacOS
- media_key_detector_ios (0.0.1):
- Flutter
- nsd_ios (0.0.1):
@@ -27,6 +30,7 @@ DEPENDENCIES:
- flutter_screen_recording (from `.symlinks/plugins/flutter_screen_recording/ios`)
- flutter_volume_controller (from `.symlinks/plugins/flutter_volume_controller/ios`)
- gamepads_ios (from `.symlinks/plugins/gamepads_ios/ios`)
- local_network_permission (from `.symlinks/plugins/local_network_permission/darwin`)
- media_key_detector_ios (from `.symlinks/plugins/media_key_detector_ios/ios`)
- nsd_ios (from `.symlinks/plugins/nsd_ios/ios`)
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
@@ -45,6 +49,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/flutter_volume_controller/ios"
gamepads_ios:
:path: ".symlinks/plugins/gamepads_ios/ios"
local_network_permission:
:path: ".symlinks/plugins/local_network_permission/darwin"
media_key_detector_ios:
:path: ".symlinks/plugins/media_key_detector_ios/ios"
nsd_ios:
@@ -59,11 +65,12 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/sign_in_with_apple/ios"
SPEC CHECKSUMS:
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
Flutter: 71a624a5bc0c04062bf19101d501e466baf2fb47
flutter_foreground_task: a159d2c2173b33699ddb3e6c2a067045d7cebb89
flutter_screen_recording: d27b9073d122b618a07ef0e407470d051b265b26
flutter_volume_controller: c2be490cb0487e8b88d0d9fc2b7e1c139a4ebccb
gamepads_ios: c75c6d31377d275b0effb9174c619e2705678c09
local_network_permission: 888f0fc169e820dff9137aa77b69fd4624485979
media_key_detector_ios: eb43ab957d4ef9084d079216b6dbac96c91d42eb
nsd_ios: 596ad79109ddd3e52d665f650f36428049e3653e
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
@@ -73,4 +80,4 @@ SPEC CHECKSUMS:
PODFILE CHECKSUM: 7ebd5c9b932b3af79d5c67e3af873118b74e970f
COCOAPODS: 1.16.2
COCOAPODS: 1.17.0

View File

@@ -616,7 +616,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -755,7 +755,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -806,7 +806,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;

View File

@@ -57,6 +57,7 @@
<array>
<string>_wahoo-fitness-tnp._tcp</string>
<string>_openbikecontrol._tcp</string>
<string>_bikecontrol-preflight._tcp</string>
</array>
<key>NSLocalNetworkUsageDescription</key>
<string>This app connects to your trainer app on your local network.</string>

View File

@@ -408,6 +408,9 @@
"license": "License",
"licenseStatus": "License Status",
"loadScreenshotForPlacement": "Load in-game screenshot for placement",
"localNetworkAccess": "Local Network access",
"localNetworkAccessDeniedIos": "BikeControl can't reach your trainer app without Local Network access. Turn it on under Settings \u2192 BikeControl \u2192 Local Network.",
"localNetworkAccessDeniedMacos": "BikeControl can't reach your trainer app without Local Network access. Turn it on under System Settings \u2192 Privacy & Security \u2192 Local Network.",
"logViewer": "Log Viewer",
"loggedInAsMail": "Logged in as {email}",
"logout": "Logout",

View File

@@ -1,13 +1,17 @@
import 'dart:io' show Platform;
import 'package:bike_control/main.dart' show recordError;
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/services/mdns_discovery_scan.dart';
import 'package:flutter/foundation.dart';
import 'package:local_network_permission/local_network_permission.dart';
import 'package:prop/mdns/service_advertiser.dart';
import 'package:prop/utils/advertised_service_registry.dart';
import 'package:prop/utils/network_address.dart';
import 'package:prop/utils/resilient_tcp_server.dart';
// Part of PermissionsSnapshot's surface — callers shouldn't need a second
// import to name the value they just read.
export 'package:local_network_permission/local_network_permission.dart' show LocalNetworkStatus;
/// A running TCP bridge server, for diagnostics.
class TcpServerInfo {
final String? label;
@@ -25,17 +29,21 @@ class TcpServerInfo {
/// Status of the permissions whose denial silently breaks WiFi/BLE bridging.
class PermissionsSnapshot {
/// iOS Local Network can't be queried directly; inferred from whether a
/// discovery scan returned anything. Null when no scan ran.
final bool? localNetworkInferred;
/// Apple's Local Network permission, measured with a Bonjour round trip.
/// Null on the platforms that have no such permission.
final LocalNetworkStatus? localNetwork;
const PermissionsSnapshot({
required this.localNetworkInferred,
required this.localNetwork,
});
static Future<PermissionsSnapshot> gather({bool? localNetworkInferred}) async {
static Future<PermissionsSnapshot> gather() async {
return PermissionsSnapshot(
localNetworkInferred: localNetworkInferred,
// Force a fresh probe: a support bundle is worthless if it reports what
// the UI happened to cache half an hour ago.
localNetwork: LocalNetworkPermission.isSupported
? await LocalNetworkAccess.status(force: true)
: null,
);
}
}
@@ -102,12 +110,7 @@ class DebugDiagnostics {
}
}
final permissions = await PermissionsSnapshot.gather(
// iOS is the only platform with a (non-queryable) "Local Network"
// permission; infer it from whether discovery saw anything. Elsewhere an
// empty scan just means no peers, so leave it unset.
localNetworkInferred: (discoveryRan && !kIsWeb && Platform.isIOS) ? discovered.isNotEmpty : null,
);
final permissions = await PermissionsSnapshot.gather();
return DebugDiagnostics(
advertised: AdvertisedServiceRegistry.instance.records,
@@ -234,11 +237,9 @@ class DebugDiagnostics {
}
}
if (permissions.localNetworkInferred != null) {
b.writeln(
' Permissions: ios-local-network='
'${permissions.localNetworkInferred! ? 'inferred-ok' : 'inferred-blocked'}',
);
final localNetwork = permissions.localNetwork;
if (localNetwork != null) {
b.writeln(' Permissions: local-network=${localNetwork.name}');
}
return b.toString().trimRight();

View File

@@ -0,0 +1,98 @@
/// Cached, app-wide view of Apple's Local Network permission.
///
/// Denial is the single most common cause of "BikeControl can't see my
/// trainer app" on iOS and macOS, and it fails completely silently — so this
/// is checked up front instead of being inferred from an empty discovery scan.
library;
import 'dart:async';
import 'package:bike_control/main.dart' show recordError;
import 'package:flutter/foundation.dart';
import 'package:local_network_permission/local_network_permission.dart';
export 'package:local_network_permission/local_network_permission.dart' show LocalNetworkStatus;
class LocalNetworkAccess {
LocalNetworkAccess._();
/// Long enough for a Bonjour round trip on a busy network, short enough not
/// to stall the tile the user just tapped.
static const probeTimeout = Duration(seconds: 3);
/// A probe costs a full network round trip and `getStatus()` runs on every
/// tile mount, tap and app resume, so results are reused for this long. The
/// answer can change behind our back (System Settings), which is what
/// [invalidate] and the short window are for.
static const cacheDuration = Duration(seconds: 30);
@visibleForTesting
static DateTime Function() now = DateTime.now;
static LocalNetworkStatus? _cached;
static DateTime? _cachedAt;
static Future<LocalNetworkStatus>? _inFlight;
/// The last known status without probing, or null if nothing is cached.
static LocalNetworkStatus? get cached => _isFresh ? _cached : null;
static bool get _isFresh {
final at = _cachedAt;
return _cached != null && at != null && now().difference(at) < cacheDuration;
}
/// The current status, probing only when the cache is stale or [force].
///
/// Concurrent callers share a single probe: two overlapping probes would
/// advertise the same Bonjour type twice and could resolve each other.
static Future<LocalNetworkStatus> status({bool force = false}) {
if (!force && _isFresh) return Future.value(_cached);
final inFlight = _inFlight;
if (inFlight != null) return inFlight;
final probe = _probe();
_inFlight = probe;
return probe.whenComplete(() {
if (identical(_inFlight, probe)) _inFlight = null;
});
}
static Future<LocalNetworkStatus> _probe() async {
LocalNetworkStatus result;
try {
result = await LocalNetworkPermission.check(timeout: probeTimeout);
} catch (e, s) {
recordError(e, s, context: 'LocalNetworkAccess.probe');
// A broken probe must not lock the user out of their trainer app.
result = LocalNetworkStatus.unknown;
}
_cached = result;
_cachedAt = now();
return result;
}
/// Drops the cache, so the next [status] re-probes.
///
/// Call this whenever the user has been somewhere they could have changed
/// the answer — the System Settings trip in particular.
static void invalidate() {
_cached = null;
_cachedAt = null;
}
/// Whether local-network features should be allowed to run.
///
/// Fails open on [LocalNetworkStatus.unknown]: that means the probe could
/// not tell (no usable network, no plugin in this build), and treating it as
/// a denial would block setups that work fine.
static Future<bool> isUsable({bool force = false}) async {
return await status(force: force) != LocalNetworkStatus.denied;
}
@visibleForTesting
static void resetForTest() {
invalidate();
_inFlight = null;
now = DateTime.now;
}
}

View File

@@ -0,0 +1,59 @@
import 'dart:io';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/main.dart' show screenshotMode;
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/utils/demo_mode.dart';
import 'package:bike_control/utils/requirements/platform.dart';
import 'package:flutter/foundation.dart';
import 'package:local_network_permission/local_network_permission.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// Gates the LAN bridging methods (MyWhoosh Link, Zwift/OpenBikeControl mDNS)
/// on Apple's Local Network permission.
///
/// Unlike every other requirement here there is no "request" step to speak
/// of: the probe behind [getStatus] *is* the request, because the system
/// prompt fires on the first Bonjour operation. Once the user has answered,
/// [call] is the only way back — the prompt never returns.
class LocalNetworkRequirement extends PlatformRequirement {
LocalNetworkRequirement()
: super(
AppLocalizations.current.localNetworkAccess,
description: !kIsWeb && Platform.isIOS
? AppLocalizations.current.localNetworkAccessDeniedIos
: AppLocalizations.current.localNetworkAccessDeniedMacos,
icon: Icons.wifi_tethering,
);
/// Only a positive denial blocks the user.
///
/// [LocalNetworkStatus.unknown] means the probe could not tell — no usable
/// network, or a build without the plugin — and failing closed on that would
/// break setups that work today.
@override
Future<bool> getStatus() async {
status = await LocalNetworkAccess.isUsable();
return status;
}
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
await LocalNetworkPermission.openSettings();
// Whatever we cached stopped being true the moment the user left for
// System Settings; the resume path re-reads the status from scratch.
LocalNetworkAccess.invalidate();
onUpdate();
}
}
/// The Local Network requirement on the platforms that have one, else nothing.
///
/// Suppressed for screenshots and demos alongside every other permission, so
/// a machine that happens to have the toggle off can't silently switch the
/// bridging methods back off mid-capture.
List<PlatformRequirement> localNetworkRequirements() {
if (screenshotMode || demoHidePermissions) return const [];
if (kIsWeb || !(Platform.isIOS || Platform.isMacOS)) return const [];
return [LocalNetworkRequirement()];
}

View File

@@ -6,6 +6,7 @@ import 'package:bike_control/pages/markdown.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/keymap/apps/supported_app.dart';
import 'package:bike_control/utils/requirements/local_network.dart';
import 'package:bike_control/widgets/ui/connection_method.dart';
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:prop/prop.dart';
@@ -41,7 +42,7 @@ class _MywhooshLinkTileState extends State<MyWhooshLinkTile> {
: isStarted
? context.i18n.checkMyWhooshConnectionScreen
: context.i18n.myWhooshLinkDescriptionLocal,
requirements: [],
requirements: localNetworkRequirements(),
showTroubleshooting: true,
onChange: (value) {
core.settings.setMyWhooshLinkEnabled(value);

View File

@@ -3,6 +3,7 @@ import 'package:bike_control/main.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/keymap/apps/supported_app.dart';
import 'package:bike_control/utils/requirements/local_network.dart';
import 'package:bike_control/widgets/ui/connection_method.dart';
import 'package:dartx/dartx.dart';
import 'package:prop/prop.dart';
@@ -44,7 +45,7 @@ class _OpenBikeProtocolTileState extends State<OpenBikeControlMdnsTile> {
: isStarted
? context.i18n.chooseBikeControlInConnectionScreen
: context.i18n.letsAppConnectOverNetwork(core.settings.getTrainerApp()?.name ?? ''),
requirements: [],
requirements: localNetworkRequirements(),
onChange: (value) {
core.settings.setObpMdnsEnabled(value);
if (!value) {

View File

@@ -5,6 +5,7 @@ import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/keymap/apps/rouvy.dart';
import 'package:bike_control/utils/keymap/apps/supported_app.dart';
import 'package:bike_control/utils/requirements/local_network.dart';
import 'package:bike_control/widgets/ui/connection_method.dart';
import 'package:flutter/material.dart';
import 'package:prop/prop.dart';
@@ -80,7 +81,7 @@ class _ZwiftTileState extends State<ZwiftMdnsTile> {
}
setState(() {});
},
requirements: [],
requirements: localNetworkRequirements(),
);
},
);

View File

@@ -22,6 +22,7 @@ import in_app_purchase_storekit
import in_app_review
import just_audio
import keypress_simulator_macos
import local_network_permission
import media_key_detector_macos
import multi_window_native
import nsd_macos
@@ -56,6 +57,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
InAppReviewPlugin.register(with: registry.registrar(forPlugin: "InAppReviewPlugin"))
JustAudioPlugin.register(with: registry.registrar(forPlugin: "JustAudioPlugin"))
KeypressSimulatorMacosPlugin.register(with: registry.registrar(forPlugin: "KeypressSimulatorMacosPlugin"))
LocalNetworkPermissionPlugin.register(with: registry.registrar(forPlugin: "LocalNetworkPermissionPlugin"))
MediaKeyDetectorPlugin.register(with: registry.registrar(forPlugin: "MediaKeyDetectorPlugin"))
MultiWindowNativePlugin.register(with: registry.registrar(forPlugin: "MultiWindowNativePlugin"))
NsdMacosPlugin.register(with: registry.registrar(forPlugin: "NsdMacosPlugin"))

View File

@@ -8,6 +8,9 @@ PODS:
- FlutterMacOS
- keypress_simulator_macos (0.0.1):
- FlutterMacOS
- local_network_permission (1.0.0):
- Flutter
- FlutterMacOS
- media_key_detector_macos (0.0.1):
- FlutterMacOS
- multi_window_native (0.0.1):
@@ -27,6 +30,7 @@ DEPENDENCIES:
- FlutterMacOS (from `Flutter/ephemeral`)
- gamepads_darwin (from `Flutter/ephemeral/.symlinks/plugins/gamepads_darwin/macos`)
- keypress_simulator_macos (from `Flutter/ephemeral/.symlinks/plugins/keypress_simulator_macos/macos`)
- local_network_permission (from `Flutter/ephemeral/.symlinks/plugins/local_network_permission/darwin`)
- media_key_detector_macos (from `Flutter/ephemeral/.symlinks/plugins/media_key_detector_macos/macos`)
- multi_window_native (from `Flutter/ephemeral/.symlinks/plugins/multi_window_native/macos`)
- nsd_macos (from `Flutter/ephemeral/.symlinks/plugins/nsd_macos/macos`)
@@ -45,6 +49,8 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/gamepads_darwin/macos
keypress_simulator_macos:
:path: Flutter/ephemeral/.symlinks/plugins/keypress_simulator_macos/macos
local_network_permission:
:path: Flutter/ephemeral/.symlinks/plugins/local_network_permission/darwin
media_key_detector_macos:
:path: Flutter/ephemeral/.symlinks/plugins/media_key_detector_macos/macos
multi_window_native:
@@ -61,9 +67,10 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
flutter_screen_capture: d089a2204161f1a0f9afb6fbb992a47f3db05f45
flutter_volume_controller: ae08bf0838e4901f299781c3ab5056dfab0c2f74
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
FlutterMacOS: c232990155153907050900a2e175c7773903ba4e
gamepads_darwin: 643b6a69e20ca678fae83781b7f7fc8f15f5d710
keypress_simulator_macos: b5c87294b03ab5a2e743873a7dabe1ff5589129d
local_network_permission: 888f0fc169e820dff9137aa77b69fd4624485979
media_key_detector_macos: f2fecf51b0cc30d6e2e4605410ae5602ff067ed8
multi_window_native: 090b0376429681c0ea21fee77f0a33c437d36fed
nsd_macos: a472240e770b92f6c6df1022403aa29c90d012e3
@@ -73,4 +80,4 @@ SPEC CHECKSUMS:
PODFILE CHECKSUM: 0fb45929fd801f111c1e68cc98ccc2d06ac5e49e
COCOAPODS: 1.16.2
COCOAPODS: 1.17.0

View File

@@ -565,7 +565,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -659,7 +659,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
@@ -709,7 +709,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;

View File

@@ -39,6 +39,7 @@
<array>
<string>_wahoo-fitness-tnp._tcp</string>
<string>_openbikecontrol._tcp</string>
<string>_bikecontrol-preflight._tcp</string>
</array>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>

View File

@@ -0,0 +1,35 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
build/
pubspec.lock

View File

@@ -0,0 +1,97 @@
License notice:
Versions of this project released prior to repository tag gpl3 were licensed
under GPL-3.0. Those versions remain available under their original
license. Versions released after that point are licensed under the
Non-Commercial License.
NON-COMMERCIAL SOFTWARE LICENSE AGREEMENT
Version 1.0
Copyright (c) 2026 OpenBikeControl UG (haftungsbeschränkt).
All rights reserved.
⸻
1. Definitions
“Software” means the source code, object code, binaries, and associated documentation made available by the Licensor under this License.
“Commercial Use” means any use of the Software, directly or indirectly, that is intended for or results in:
• monetary compensation,
• sale, licensing, or subscription fees,
• advertising or sponsorship revenue,
• inclusion in a product or service that is sold or monetized,
• distribution through paid applications or application marketplaces.
“Licensor” means the copyright holder.
⸻
2. Grant of License
Subject to the terms of this License, the Licensor grants you a non-exclusive, non-transferable, revocable license to:
• use the Software for personal, educational, or internal evaluation purposes only;
• modify the Software for non-commercial purposes;
• redistribute the Software only in source form, free of charge, and only under this same License.
⸻
3. Restrictions
You may not, without prior written permission from the Licensor:
• use the Software for any Commercial Use;
• distribute the Software as part of a paid or monetized product or service;
• distribute the Software via application marketplaces (including but not limited to Apple App Store or Google Play) where the application itself or related services are monetized;
• sublicense, sell, rent, or lease the Software.
⸻
4. Attribution
All copies and derivative works must retain:
• this License text;
• all existing copyright notices.
⸻
5. No Patent License
This License does not grant any patent rights.
⸻
6. Termination
Any violation of this License automatically terminates your rights under this License.
Upon termination, you must cease all use and distribution of the Software.
⸻
7. Disclaimer of Warranty
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND.
⸻
8. Limitation of Liability
IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE OF THE SOFTWARE.
⸻
9. Governing Law
This License shall be governed by the laws of [YOUR COUNTRY], excluding conflict-of-law rules.
⸻
10. Commercial Licensing
Commercial use is available under separate commercial license terms.
Contact: jonas@openbikecontrol.org
⸻
End of License

View File

@@ -0,0 +1,13 @@
analyzer:
exclude:
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

View File

@@ -0,0 +1,228 @@
import Foundation
import Network
import dnssd
#if os(iOS)
import Flutter
import UIKit
#elseif os(macOS)
import Cocoa
import FlutterMacOS
#endif
/// Bonjour type used solely to probe the Local Network permission.
///
/// It must also be listed in the host app's `NSBonjourServices`, otherwise the
/// browse is rejected for a reason that has nothing to do with the permission
/// and every probe reports `denied`.
private let preflightServiceType = "_bikecontrol-preflight._tcp"
/// Apple ships no authorization-status API for Local Network privacy — not on
/// iOS 14...26, not on macOS 15...26. The only reliable signal is to actually
/// perform a Bonjour round trip and watch how it fails:
///
/// * the browser discovering our own listener -> granted
/// * `kDNSServiceErr_PolicyDenied` (-65570) -> denied
/// * neither, before the timeout -> unknown
///
/// `unknown` is a real outcome, not an error: a device with no network at all
/// never completes the round trip even though the permission is fine. Callers
/// must not treat it as a denial.
public class LocalNetworkPermissionPlugin: NSObject, FlutterPlugin {
private static let channelName = "bike_control/local_network_permission"
public static func register(with registrar: FlutterPluginRegistrar) {
#if os(iOS)
let messenger = registrar.messenger()
#else
let messenger = registrar.messenger
#endif
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger)
registrar.addMethodCallDelegate(LocalNetworkPermissionPlugin(), channel: channel)
}
/// Guards `probe`. Two concurrent probes would advertise two instances of
/// the same service type and each browser could resolve the *other* one, so
/// only one runs at a time and later callers join the one in flight.
private let lock = NSLock()
private var probe: Probe?
private var pending: [FlutterResult] = []
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "check":
let arguments = call.arguments as? [String: Any]
let timeoutMs = arguments?["timeoutMs"] as? Int ?? 4000
check(timeoutMs: timeoutMs, result: result)
case "openSettings":
openSettings()
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
private func check(timeoutMs: Int, result: @escaping FlutterResult) {
lock.lock()
pending.append(result)
if probe != nil {
// A probe is already running; this caller rides along on its outcome.
lock.unlock()
return
}
guard let probe = Probe(timeoutMs: timeoutMs) else {
let waiting = pending
pending = []
lock.unlock()
// NWListener creation only fails on malformed parameters, which are
// hard-coded here — surface it rather than reporting a fake denial.
let error = FlutterError(
code: "probe_unavailable",
message: "Could not create the local network probe",
details: nil
)
for callback in waiting {
callback(error)
}
return
}
self.probe = probe
lock.unlock()
probe.start { [weak self] outcome in
guard let self else { return }
self.lock.lock()
let waiting = self.pending
self.pending = []
self.probe = nil
self.lock.unlock()
for callback in waiting {
callback(outcome)
}
}
}
private func openSettings() {
#if os(iOS)
// Lands on BikeControl's own settings page, which is where the Local
// Network toggle lives; iOS has no deep link to the toggle itself.
guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
DispatchQueue.main.async {
UIApplication.shared.open(url)
}
#elseif os(macOS)
// macOS 26 has no `Privacy_LocalNetwork` anchor in the Settings anchor
// table (unlike `Privacy_Bluetooth`), so an unknown anchor degrades to
// the Privacy & Security pane — still the right place to land.
guard
let url = URL(
string: "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork")
else { return }
NSWorkspace.shared.open(url)
#endif
}
}
/// One `NWListener` + `NWBrowser` pair, reporting exactly once.
private final class Probe {
private let queue = DispatchQueue(label: "app.bikecontrol.localNetworkProbe")
private let listener: NWListener
private let browser: NWBrowser
private let timeoutMs: Int
private var completion: ((String) -> Void)?
private var timeout: DispatchWorkItem?
init?(timeoutMs: Int) {
guard
let listener = try? NWListener(
using: NWParameters(tls: .none, tcp: NWProtocolTCP.Options()))
else {
return nil
}
self.listener = listener
self.browser = NWBrowser(for: .bonjour(type: preflightServiceType, domain: nil), using: .tcp)
self.timeoutMs = timeoutMs
}
func start(completion: @escaping (String) -> Void) {
queue.async {
self.completion = completion
let timeout = DispatchWorkItem { [weak self] in
// Nothing was discovered and nothing was denied. Most likely there is
// no usable network at all — report neither, and let the caller keep
// whatever it already assumed.
self?.finish("unknown")
}
self.timeout = timeout
self.queue.asyncAfter(deadline: .now() + .milliseconds(self.timeoutMs), execute: timeout)
// A listener without a connection handler refuses to start.
self.listener.newConnectionHandler = { $0.cancel() }
self.listener.service = NWListener.Service(
name: UUID().uuidString, type: preflightServiceType)
self.listener.stateUpdateHandler = { [weak self] state in
// Only a denial is conclusive here: when Local Network is off the
// listener otherwise reports `.ready` and silently advertises nothing,
// which is exactly why the browser has to be the primary signal.
switch state {
case .failed(let error), .waiting(let error):
if isPolicyDenied(error) {
self?.finish("denied")
}
default:
break
}
}
self.listener.start(queue: self.queue)
self.browser.stateUpdateHandler = { [weak self] state in
switch state {
case .failed(let error), .waiting(let error):
if isPolicyDenied(error) {
self?.finish("denied")
}
// Other `.waiting` reasons (no router, no interface) are transient and
// say nothing about the permission — let the timeout call those.
default:
break
}
}
self.browser.browseResultsChangedHandler = { [weak self] results, _ in
// Any result proves Bonjour traffic reaches this process. It is
// usually our own listener, but another BikeControl on the LAN is
// just as good a proof.
if !results.isEmpty {
self?.finish("granted")
}
}
self.browser.start(queue: self.queue)
}
}
/// Reports `outcome` once and tears everything down. Always on `queue`.
private func finish(_ outcome: String) {
guard let completion else { return }
self.completion = nil
timeout?.cancel()
timeout = nil
listener.stateUpdateHandler = nil
listener.newConnectionHandler = nil
browser.stateUpdateHandler = nil
browser.browseResultsChangedHandler = nil
listener.cancel()
browser.cancel()
completion(outcome)
}
}
/// True for `kDNSServiceErr_PolicyDenied` (-65570), the error the Network
/// framework raises when Local Network privacy blocks the operation.
private func isPolicyDenied(_ error: NWError) -> Bool {
if case .dns(let code) = error {
return code == DNSServiceErrorType(kDNSServiceErr_PolicyDenied)
}
return false
}

View File

@@ -0,0 +1,27 @@
#
# Shared iOS/macOS pod for the Local Network privacy probe.
# Run `pod lib lint local_network_permission.podspec` to validate.
#
Pod::Spec.new do |s|
s.name = 'local_network_permission'
s.version = '1.0.0'
s.summary = "Probes Apple's Local Network privacy permission."
s.description = <<-DESC
Apple ships no authorization-status API for the Local Network permission, so
this plugin infers it from an NWListener/NWBrowser Bonjour round trip.
DESC
s.homepage = 'https://bikecontrol.app'
s.license = { :file => '../LICENSE' }
s.author = { 'BikeControl' => 'jonas@bikecontrol.app' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
s.ios.dependency 'Flutter'
s.ios.deployment_target = '15.0'
s.osx.dependency 'FlutterMacOS'
s.osx.deployment_target = '12.0'
end

View File

@@ -0,0 +1,85 @@
/// Apple's Local Network privacy permission, which has no status API.
///
/// Denial is silent: Bonjour browses return nothing forever, advertisements
/// never leave the device and LAN sockets simply never see traffic. Nothing
/// throws, so an app that only watches for errors cannot tell "permission is
/// off" from "there is nothing out there". This probes it instead.
library;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// Outcome of one Local Network probe.
enum LocalNetworkStatus {
/// A Bonjour round trip completed, so LAN traffic reaches this process.
granted,
/// The platform reported `kDNSServiceErr_PolicyDenied` (-65570).
denied,
/// Neither happened before the timeout, or this platform has no such
/// permission at all.
///
/// Not an error, and explicitly not a denial: a device with no usable
/// network never completes the round trip even when the permission is fine.
/// Callers must fail open on this.
unknown,
}
/// Probes (and, the first time, requests) the Local Network permission.
///
/// The probe is not silent on first use — it triggers the system prompt,
/// which is the point: the alternative is the permission never being asked
/// for until some LAN feature has already failed. Once the user has answered,
/// further probes reuse the decision without prompting again.
class LocalNetworkPermission {
LocalNetworkPermission._();
@visibleForTesting
static const channel = MethodChannel('bike_control/local_network_permission');
/// Whether this platform gates local network access behind a permission.
static bool get isSupported =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS);
/// Runs one probe, resolving within roughly [timeout].
///
/// Throws [PlatformException] if the native probe could not be built; a
/// missing plugin (older build, unsupported platform) yields [unknown]
/// rather than an error, because "we cannot tell" is the honest answer.
static Future<LocalNetworkStatus> check({
Duration timeout = const Duration(seconds: 4),
}) async {
if (!isSupported) return LocalNetworkStatus.unknown;
final String? outcome;
try {
outcome = await channel
.invokeMethod<String>('check', {'timeoutMs': timeout.inMilliseconds})
// The native side has its own deadline; this only catches a probe
// that wedged entirely. Without it a caller awaiting the result
// would wait forever, and so would everyone queued behind it.
.timeout(timeout + const Duration(seconds: 2), onTimeout: () => null);
} on MissingPluginException {
return LocalNetworkStatus.unknown;
}
return switch (outcome) {
'granted' => LocalNetworkStatus.granted,
'denied' => LocalNetworkStatus.denied,
_ => LocalNetworkStatus.unknown,
};
}
/// Opens the place where the user can flip the toggle: BikeControl's own
/// settings page on iOS, the Privacy & Security pane on macOS.
static Future<void> openSettings() async {
if (!isSupported) return;
try {
await channel.invokeMethod<void>('openSettings');
} on MissingPluginException {
// Nothing to open on a build without the plugin.
}
}
}

View File

@@ -0,0 +1,28 @@
name: local_network_permission
description: "Probes Apple's Local Network privacy permission on iOS and macOS, which has no authorization-status API."
version: 1.0.0
publish_to: none
environment:
sdk: '>=3.8.1 <4.0.0'
# sharedDarwinSource needs Flutter 3.7+.
flutter: '>=3.7.0'
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
flutter:
plugin:
platforms:
ios:
sharedDarwinSource: true
pluginClass: LocalNetworkPermissionPlugin
macos:
sharedDarwinSource: true
pluginClass: LocalNetworkPermissionPlugin

View File

@@ -0,0 +1,105 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:local_network_permission/local_network_permission.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final calls = <MethodCall>[];
late Object? reply;
void mockNative(Object? Function(MethodCall call) handler) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
(call) async {
calls.add(call);
return handler(call);
},
);
}
setUp(() {
calls.clear();
reply = 'granted';
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
mockNative((_) => reply);
});
tearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
null,
);
});
group('check', () {
test('maps the native outcome strings', () async {
reply = 'granted';
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.granted);
reply = 'denied';
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.denied);
reply = 'unknown';
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.unknown);
});
test('an unrecognised or absent outcome is unknown, never denied', () async {
reply = 'something-new';
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.unknown);
reply = null;
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.unknown);
});
test('forwards the timeout in milliseconds', () async {
await LocalNetworkPermission.check(timeout: const Duration(milliseconds: 1500));
expect(calls.single.method, 'check');
expect(calls.single.arguments, {'timeoutMs': 1500});
});
test('is unknown without touching the channel off iOS/macOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.unknown);
expect(calls, isEmpty);
});
test('is unknown when the plugin is missing, rather than throwing', () async {
mockNative((call) => throw MissingPluginException('no ${call.method}'));
expect(await LocalNetworkPermission.check(), LocalNetworkStatus.unknown);
});
test('gives up on a wedged native probe instead of hanging', () async {
mockNative((_) => Completer<String>().future);
expect(
await LocalNetworkPermission.check(timeout: const Duration(milliseconds: 20)),
LocalNetworkStatus.unknown,
);
});
test('surfaces a native probe failure', () async {
mockNative((_) => throw PlatformException(code: 'probe_unavailable'));
expect(LocalNetworkPermission.check(), throwsA(isA<PlatformException>()));
});
});
group('openSettings', () {
test('invokes the native opener on macOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
await LocalNetworkPermission.openSettings();
expect(calls.single.method, 'openSettings');
});
test('is a no-op off iOS/macOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
await LocalNetworkPermission.openSettings();
expect(calls, isEmpty);
});
test('tolerates a missing plugin', () async {
mockNative((call) => throw MissingPluginException('no ${call.method}'));
await expectLater(LocalNetworkPermission.openSettings(), completes);
});
});
}

View File

@@ -976,10 +976,10 @@ packages:
dependency: "direct main"
description:
name: intl
sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5"
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.2"
version: "0.20.3"
intl_utils:
dependency: "direct dev"
description:
@@ -1120,6 +1120,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.9"
local_network_permission:
dependency: "direct main"
description:
path: "packages/local_network_permission"
relative: true
source: path
version: "1.0.0"
logger:
dependency: transitive
description:
@@ -1148,10 +1155,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -1206,10 +1213,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
mime:
dependency: transitive
description:
@@ -1881,10 +1888,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
time:
dependency: transitive
description:
@@ -2026,10 +2033,10 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
version:
dependency: "direct main"
description:

View File

@@ -60,6 +60,8 @@ dependencies:
window_manager: ^0.5.1
multi_window_native:
path: packages/multi_window_native
local_network_permission:
path: packages/local_network_permission
flutter_overlay_window: ^0.5.0
live_activities: ^2.4.9
device_info_plus: ^12.1.0

View File

@@ -43,7 +43,7 @@ void main() {
TcpServerInfo(label: 'OpenBikeControl', port: 36867, listening: true, hasClient: true),
],
permissions: const PermissionsSnapshot(
localNetworkInferred: true,
localNetwork: LocalNetworkStatus.granted,
),
);
@@ -59,7 +59,7 @@ void main() {
expect(text, contains('en0/192.168.1.9 = 40 (advertised)'));
expect(text, contains('utun0/10.2.0.2 = -60 (virtual)'));
expect(text, contains('OpenBikeControl :36867 listening · 1 client'));
expect(text, contains('ios-local-network=inferred-ok'));
expect(text, contains('local-network=granted'));
});
test('toText marks discovery as skipped when it did not run', () {
@@ -72,7 +72,7 @@ void main() {
discoveryRan: false,
addressReport: const AddressPickReport(chosen: null, candidates: []),
servers: const [],
permissions: const PermissionsSnapshot(localNetworkInferred: null),
permissions: const PermissionsSnapshot(localNetwork: null),
);
expect(diag.toText(), contains('Discovered on network:'));
@@ -89,7 +89,7 @@ void main() {
discoveryRan: true,
addressReport: AddressPickReport(chosen: InternetAddress('192.168.1.9'), candidates: candidates),
servers: const [],
permissions: const PermissionsSnapshot(localNetworkInferred: null),
permissions: const PermissionsSnapshot(localNetwork: null),
);
test('names the tunnel interface when a VPN carries a routable IPv4', () {

View File

@@ -0,0 +1,128 @@
import 'dart:async';
import 'package:bike_control/services/local_network_access.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:local_network_permission/local_network_permission.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
var probes = 0;
late Object? Function() respond;
late DateTime clock;
void mockNative(Object? Function() handler) {
respond = handler;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
(call) async {
if (call.method != 'check') return null;
probes++;
return respond();
},
);
}
setUp(() {
probes = 0;
clock = DateTime(2026, 8, 20, 12);
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
LocalNetworkAccess.resetForTest();
LocalNetworkAccess.now = () => clock;
mockNative(() => 'granted');
});
tearDown(() {
debugDefaultTargetPlatformOverride = null;
LocalNetworkAccess.resetForTest();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
null,
);
});
test('probes once and serves the rest from cache', () async {
expect(await LocalNetworkAccess.status(), LocalNetworkStatus.granted);
expect(await LocalNetworkAccess.status(), LocalNetworkStatus.granted);
expect(probes, 1);
});
test('re-probes once the cache goes stale', () async {
await LocalNetworkAccess.status();
clock = clock.add(LocalNetworkAccess.cacheDuration - const Duration(seconds: 1));
await LocalNetworkAccess.status();
expect(probes, 1, reason: 'still inside the cache window');
clock = clock.add(const Duration(seconds: 2));
await LocalNetworkAccess.status();
expect(probes, 2);
});
test('force re-probes even on a fresh cache', () async {
await LocalNetworkAccess.status();
await LocalNetworkAccess.status(force: true);
expect(probes, 2);
});
test('invalidate drops the cache', () async {
await LocalNetworkAccess.status();
expect(LocalNetworkAccess.cached, LocalNetworkStatus.granted);
LocalNetworkAccess.invalidate();
expect(LocalNetworkAccess.cached, isNull);
await LocalNetworkAccess.status();
expect(probes, 2);
});
test('cached reports nothing once the entry is stale', () async {
await LocalNetworkAccess.status();
clock = clock.add(LocalNetworkAccess.cacheDuration);
expect(LocalNetworkAccess.cached, isNull);
});
test('concurrent callers share a single probe', () async {
// Two overlapping probes would advertise the same Bonjour type twice and
// could resolve each other, so overlap has to collapse into one.
final gate = Completer<void>();
mockNative(() => gate.future.then((_) => 'denied'));
final first = LocalNetworkAccess.status();
final second = LocalNetworkAccess.status();
gate.complete();
expect(await first, LocalNetworkStatus.denied);
expect(await second, LocalNetworkStatus.denied);
expect(probes, 1);
});
test('a probe that failed does not wedge later probes', () async {
mockNative(() => throw PlatformException(code: 'probe_unavailable'));
expect(await LocalNetworkAccess.status(), LocalNetworkStatus.unknown);
mockNative(() => 'granted');
expect(await LocalNetworkAccess.status(force: true), LocalNetworkStatus.granted);
});
group('isUsable', () {
test('blocks only on a positive denial', () async {
mockNative(() => 'denied');
expect(await LocalNetworkAccess.isUsable(), isFalse);
});
test('fails open when the probe could not tell', () async {
mockNative(() => 'unknown');
expect(await LocalNetworkAccess.isUsable(), isTrue);
});
test('fails open when the native probe errors out', () async {
// A broken probe must never lock a working setup out of its trainer app.
mockNative(() => throw PlatformException(code: 'probe_unavailable'));
expect(await LocalNetworkAccess.isUsable(), isTrue);
});
test('allows a grant', () async {
expect(await LocalNetworkAccess.isUsable(), isTrue);
});
});
}

View File

@@ -0,0 +1,106 @@
import 'dart:io';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/main.dart' show screenshotMode;
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/utils/requirements/local_network.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:local_network_permission/local_network_permission.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final calls = <String>[];
late String outcome;
setUp(() async {
await AppLocalizations.load(const Locale('en'));
calls.clear();
outcome = 'granted';
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
LocalNetworkAccess.resetForTest();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
(call) async {
calls.add(call.method);
return call.method == 'check' ? outcome : null;
},
);
});
tearDown(() {
debugDefaultTargetPlatformOverride = null;
LocalNetworkAccess.resetForTest();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
LocalNetworkPermission.channel,
null,
);
});
test('is satisfied when the permission is granted', () async {
expect(await LocalNetworkRequirement().getStatus(), isTrue);
});
test('is unsatisfied only on a positive denial', () async {
outcome = 'denied';
final requirement = LocalNetworkRequirement();
expect(await requirement.getStatus(), isFalse);
expect(requirement.status, isFalse);
});
test('stays satisfied when the probe cannot tell', () async {
// No usable network is not the same as a denial; blocking here would break
// setups that work.
outcome = 'unknown';
expect(await LocalNetworkRequirement().getStatus(), isTrue);
});
test('call opens settings and drops the cached answer', () async {
outcome = 'denied';
final requirement = LocalNetworkRequirement();
await requirement.getStatus();
expect(LocalNetworkAccess.cached, LocalNetworkStatus.denied);
var updates = 0;
await requirement.call(_NullContext(), () => updates++);
expect(calls, contains('openSettings'));
expect(LocalNetworkAccess.cached, isNull, reason: 'the user may have just flipped the toggle');
expect(updates, 1);
});
test('carries a name and a description for the permission sheet', () {
final requirement = LocalNetworkRequirement();
expect(requirement.name, isNotEmpty);
expect(requirement.description, isNotNull);
// macOS users need the System Settings path; iOS users need theirs.
expect(requirement.description, contains('Local Network'));
});
test('is suppressed in screenshot mode', () {
// Marketing captures must not depend on the toggle state of whichever
// machine runs them.
screenshotMode = true;
addTearDown(() => screenshotMode = false);
expect(localNetworkRequirements(), isEmpty);
});
test('is supplied on Apple platforms and nowhere else', () {
// Guarded on dart:io rather than debugDefaultTargetPlatformOverride, so
// this asserts against the host running the suite.
if (Platform.isIOS || Platform.isMacOS) {
expect(localNetworkRequirements().single, isA<LocalNetworkRequirement>());
} else {
expect(localNetworkRequirements(), isEmpty);
}
});
}
/// [LocalNetworkRequirement.call] never touches its context — it delegates
/// straight to the platform channel — so a stub is enough.
class _NullContext implements BuildContext {
@override
dynamic noSuchMethod(Invocation invocation) => null;
}

View File

@@ -13,7 +13,7 @@ DebugDiagnostics _fixture() => const DebugDiagnostics(
discoveryRan: true,
addressReport: AddressPickReport(chosen: null, candidates: []),
servers: [],
permissions: PermissionsSnapshot(localNetworkInferred: true),
permissions: PermissionsSnapshot(localNetwork: LocalNetworkStatus.granted),
);
void main() {