Add bug preventing the web-handoff workflow from working with self-hosted instances

This commit is contained in:
Roland Geider
2026-06-05 13:36:54 +02:00
parent 3cbe7c99dc
commit a4425354fc
4 changed files with 49 additions and 31 deletions

View File

@@ -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).

View File

@@ -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<String> 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<String> issueAppAuthState(String serverUrl) async {
final rng = Random.secure();
final bytes = List<int>.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<bool> 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<String?> 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=<jwt>` 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) {

View File

@@ -115,7 +115,7 @@ class _AuthCardState extends ConsumerState<AuthCard> {
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,

View File

@@ -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);
});
});
}