From a4425354fc63a71903446e63cb7d63bc5f20e7e4 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 5 Jun 2026 13:36:54 +0200 Subject: [PATCH] Add bug preventing the web-handoff workflow from working with self-hosted instances --- lib/helpers/consts.dart | 3 ++ lib/providers/app_link_router.dart | 28 ++++++++------ lib/widgets/auth/auth_card.dart | 2 +- test/providers/app_link_router_test.dart | 47 ++++++++++++++---------- 4 files changed, 49 insertions(+), 31 deletions(-) diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 40173c5e3..0f6238a2c 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -86,6 +86,9 @@ const SECURE_STORAGE_REFRESH_TOKEN = 'wger_refresh_token'; /// (not a secret, just a one-shot nonce echoed back by the server). const PREFS_APP_AUTH_STATE = 'appAuthState'; const PREFS_APP_AUTH_STATE_AT = 'appAuthStateAt'; +// The server URL the handoff was started for, round-tripped with the nonce so +// the returning token is redeemed against the same (e.g. self-hosted) server. +const PREFS_APP_AUTH_SERVER = 'appAuthServer'; /// True once PowerSync has been reachable for this user at least once /// (i.e. its liveness probe returned 200). diff --git a/lib/providers/app_link_router.dart b/lib/providers/app_link_router.dart index 2a8ec3788..f3190b175 100644 --- a/lib/providers/app_link_router.dart +++ b/lib/providers/app_link_router.dart @@ -38,36 +38,40 @@ const APP_AUTH_HOST = 'app-auth'; /// via web" again const APP_AUTH_STATE_TTL = Duration(minutes: 10); -/// Generates a 256-bit nonce, persists it as the pending handoff state and -/// returns it for inclusion in the launch URL. Each call rotates the value, -/// so a previously-issued (but unused) state is invalidated. -Future issueAppAuthState() async { +/// Generates a 256-bit nonce, persists it (with [serverUrl]) as the pending +/// handoff state and returns it for inclusion in the launch URL. Each call +/// rotates the value, so a previously-issued (but unused) state is invalidated. +Future issueAppAuthState(String serverUrl) async { final rng = Random.secure(); final bytes = List.generate(32, (_) => rng.nextInt(256)); final state = base64UrlEncode(bytes).replaceAll('=', ''); final prefs = PreferenceHelper.asyncPref; await prefs.setString(PREFS_APP_AUTH_STATE, state); + await prefs.setString(PREFS_APP_AUTH_SERVER, serverUrl); await prefs.setInt(PREFS_APP_AUTH_STATE_AT, clock.now().millisecondsSinceEpoch); return state; } /// Consumes any outstanding handoff state and verifies that [received] /// matches it within [APP_AUTH_STATE_TTL]. Always clears the stored value -/// (single use), regardless of outcome. Returns true on match. -Future consumeAppAuthState(String? received) async { +/// (single use), regardless of outcome. Returns the server URL the handoff was +/// issued for on a valid match, or null on any rejection. +Future consumeAppAuthState(String? received) async { final prefs = PreferenceHelper.asyncPref; final stored = await prefs.getString(PREFS_APP_AUTH_STATE); final issuedAt = await prefs.getInt(PREFS_APP_AUTH_STATE_AT) ?? 0; + final serverUrl = await prefs.getString(PREFS_APP_AUTH_SERVER); await prefs.remove(PREFS_APP_AUTH_STATE); await prefs.remove(PREFS_APP_AUTH_STATE_AT); + await prefs.remove(PREFS_APP_AUTH_SERVER); if (stored == null || received == null || received.isEmpty) { - return false; + return null; } final ageMs = clock.now().millisecondsSinceEpoch - issuedAt; if (ageMs > APP_AUTH_STATE_TTL.inMilliseconds) { - return false; + return null; } - return stored == received; + return stored == received ? serverUrl : null; } /// Routes incoming `wger://app-auth#token=` deep links into the auth @@ -113,14 +117,16 @@ class AppLinkRouter { return; } final state = fragmentParam(uri, 'state'); - if (!await consumeAppAuthState(state)) { + // Returns the server URL the handoff was started for, so a self-hosted + // token is redeemed against its own server, not the default. + final serverUrl = await consumeAppAuthState(state); + if (serverUrl == null) { // Unsolicited link (no outstanding state), stale (past TTL), or state // mismatch, all three look the same from here and are all rejected by // design. Login-CSRF defence: only accept handoffs the app started itself. _logger.warning('Rejecting handoff deep link with bad/missing state: $uri'); return; } - final serverUrl = await AuthNotifier.getServerUrlFromPrefs(); try { await _ref.read(authProvider.notifier).login('', '', serverUrl, token); } catch (e, st) { diff --git a/lib/widgets/auth/auth_card.dart b/lib/widgets/auth/auth_card.dart index 9e6f08fc2..486e248fa 100644 --- a/lib/widgets/auth/auth_card.dart +++ b/lib/widgets/auth/auth_card.dart @@ -115,7 +115,7 @@ class _AuthCardState extends ConsumerState { if (serverUrl.isEmpty) { serverUrl = kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD; } - final state = await issueAppAuthState(); + final state = await issueAppAuthState(serverUrl); await launchUrl( Uri.parse('$serverUrl/user/app-auth/?state=$state'), mode: LaunchMode.externalApplication, diff --git a/test/providers/app_link_router_test.dart b/test/providers/app_link_router_test.dart index c99b7b85e..ec9212984 100644 --- a/test/providers/app_link_router_test.dart +++ b/test/providers/app_link_router_test.dart @@ -87,32 +87,41 @@ void main() { }); group('issueAppAuthState / consumeAppAuthState', () { + const server = 'https://my.wger.example'; + setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); }); - test('a freshly issued state is accepted exactly once', () async { - final state = await issueAppAuthState(); + test('a valid match round-trips the server URL the handoff was issued for', () async { + final state = await issueAppAuthState(server); expect(state, isNotEmpty); - expect(await consumeAppAuthState(state), isTrue); + // The returning token must be redeemed against the issuing (self-hosted) + // server, not a default. + expect(await consumeAppAuthState(state), server); + }); + + test('a freshly issued state is accepted exactly once', () async { + final state = await issueAppAuthState(server); + expect(await consumeAppAuthState(state), server); // Single-use: the second consume sees an empty store. - expect(await consumeAppAuthState(state), isFalse); + expect(await consumeAppAuthState(state), isNull); }); test('a mismatched state is rejected and still clears the pending one', () async { - await issueAppAuthState(); - expect(await consumeAppAuthState('not-the-real-one'), isFalse); + await issueAppAuthState(server); + expect(await consumeAppAuthState('not-the-real-one'), isNull); // The pending state was wiped — replaying the right value now also fails. - expect(await consumeAppAuthState('anything'), isFalse); + expect(await consumeAppAuthState('anything'), isNull); }); test('null and empty received values are rejected', () async { - await issueAppAuthState(); - expect(await consumeAppAuthState(null), isFalse); + await issueAppAuthState(server); + expect(await consumeAppAuthState(null), isNull); }); - test('consume without any pending state returns false', () async { - expect(await consumeAppAuthState('anything'), isFalse); + test('consume without any pending state returns null', () async { + expect(await consumeAppAuthState('anything'), isNull); }); test('state past the TTL is rejected', () async { @@ -120,28 +129,28 @@ void main() { final t0 = DateTime(2026, 1, 1, 12); String? issued; await withClock(Clock.fixed(t0), () async { - issued = await issueAppAuthState(); + issued = await issueAppAuthState(server); }); final later = t0.add(APP_AUTH_STATE_TTL + const Duration(seconds: 1)); final result = await withClock( Clock.fixed(later), () => consumeAppAuthState(issued), ); - expect(result, isFalse); + expect(result, isNull); }); test('issuing twice rotates the value', () async { - final first = await issueAppAuthState(); - final second = await issueAppAuthState(); + final first = await issueAppAuthState(server); + final second = await issueAppAuthState(server); expect(first, isNot(second)); // Only the second one is now consumable. - expect(await consumeAppAuthState(first), isFalse); + expect(await consumeAppAuthState(first), isNull); }); test('rotation invariant: each issue must invalidate the previous', () async { - final first = await issueAppAuthState(); - await issueAppAuthState(); - expect(await consumeAppAuthState(first), isFalse); + final first = await issueAppAuthState(server); + await issueAppAuthState(server); + expect(await consumeAppAuthState(first), isNull); }); }); }