From 87a40fd4e64ea1adcbbd3651a80fd6409fef263a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 15 May 2026 16:28:57 +0200 Subject: [PATCH] Switch the pasted-token field from DRF tokens to refresh tokens --- .../exceptions/mfa_required_exception.dart | 35 ++ lib/database/powersync/tables/exercise.dart | 4 +- lib/database/powersync/tables/nutrition.dart | 2 +- lib/helpers/consts.dart | 2 +- lib/helpers/jwt.dart | 4 +- lib/l10n/app_en.arb | 22 +- lib/models/exercises/exercise_filters.dart | 2 +- lib/models/nutrition/ingredient.dart | 2 +- lib/models/nutrition/ingredient_filters.dart | 2 +- lib/models/nutrition/ingredient_image.dart | 2 +- lib/models/nutrition/log.dart | 2 +- lib/models/nutrition/meal_item.dart | 2 +- lib/powersync/connector.dart | 4 +- lib/providers/auth_http_client.dart | 6 +- lib/providers/auth_notifier.dart | 271 +++++++++---- lib/providers/auth_notifier.g.dart | 2 +- lib/providers/exercise_filter_state.dart | 2 +- lib/providers/exercise_filters_riverpod.dart | 4 +- lib/providers/exercise_repository.dart | 4 +- lib/providers/gallery_notifier.dart | 2 +- lib/providers/gallery_repository.dart | 2 +- lib/providers/gym_log_notifier.dart | 2 +- lib/providers/helpers.dart | 4 +- lib/providers/ingredient_notifier.dart | 2 +- lib/providers/media_url_prefix_notifier.dart | 6 +- .../media_url_prefix_notifier.g.dart | 16 +- lib/providers/routines_notifier.dart | 8 +- lib/providers/routines_repository.dart | 4 +- lib/providers/wger_base.dart | 2 +- lib/screens/auth_screen.dart | 64 +-- ...en_field.dart => refresh_token_field.dart} | 36 +- lib/widgets/core/wger_image.dart | 2 +- lib/widgets/dashboard/widgets/weight.dart | 4 +- lib/widgets/exercises/autocompleter.dart | 4 +- lib/widgets/exercises/images.dart | 2 +- lib/widgets/nutrition/forms.dart | 2 +- lib/widgets/nutrition/ingredient_dialogs.dart | 4 +- lib/widgets/nutrition/meal.dart | 2 +- .../nutrition/nutritional_plans_list.dart | 2 +- lib/widgets/nutrition/widgets.dart | 4 +- lib/widgets/routines/forms/repetitions.dart | 2 +- lib/widgets/routines/forms/weight.dart | 2 +- lib/widgets/search/language_dropdown.dart | 2 +- test/auth/auth_notifier_login_test.dart | 370 ++++++++++++++++++ test/auth/auth_notifier_login_test.mocks.dart | 254 ++++++++++++ test/auth/auth_notifier_powersync_test.dart | 4 +- test/auth/auth_notifier_test.dart | 22 +- test/auth/auth_screen_test.dart | 167 ++++---- test/auth/auth_screen_test.mocks.dart | 36 ++ test/core/validators_test.mocks.dart | 35 +- .../exercises/add_exercise_notifier_test.dart | 2 +- test/exercises/add_exercise_state_test.dart | 4 +- .../exercise_filters_notifier_test.dart | 2 +- test/fake_connectivity.dart | 4 +- test/helpers/in_memory_drift.dart | 2 +- test/nutrition/ingredient_typeahead_test.dart | 4 +- test/nutrition/nutrition_provider_test.dart | 4 +- test/nutrition/nutrition_repository_test.dart | 4 +- .../nutrition/nutritional_meal_form_test.dart | 2 +- .../nutritional_meal_item_form_test.dart | 2 +- .../nutritional_plan_screen_test.dart | 2 +- .../nutritional_plans_screen_test.dart | 2 +- test/powersync/connector_test.dart | 2 +- test/providers/helpers_test.dart | 2 +- .../media_url_prefix_notifier_test.dart | 4 +- test/routine/gym_log_notifier_test.dart | 2 +- test/routine/gym_mode/gym_mode_test.dart | 10 +- .../helpers/routine_form_test_overrides.dart | 4 +- test/routine/models/log_test.dart | 4 +- .../routines_provider_repository_test.dart | 2 +- test/routine/routines_provider_test.dart | 4 +- test/routine/routines_repository_test.dart | 10 +- test/routine/routines_screen_test.dart | 2 +- .../routine/workout_logs_repository_test.dart | 4 +- test/screens/recovery_screens_test.dart | 2 +- test/widgets/core/error_test.dart | 2 +- 76 files changed, 1191 insertions(+), 339 deletions(-) create mode 100644 lib/core/exceptions/mfa_required_exception.dart rename lib/widgets/auth/{api_token_field.dart => refresh_token_field.dart} (53%) create mode 100644 test/auth/auth_notifier_login_test.dart create mode 100644 test/auth/auth_notifier_login_test.mocks.dart diff --git a/lib/core/exceptions/mfa_required_exception.dart b/lib/core/exceptions/mfa_required_exception.dart new file mode 100644 index 000000000..f90f5f9b2 --- /dev/null +++ b/lib/core/exceptions/mfa_required_exception.dart @@ -0,0 +1,35 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +/// Thrown when an `allauth.headless` login or signup response indicates that +/// the user must complete a second authentication factor before the session +/// can be issued tokens. +/// +/// The [sessionToken] carries the short-lived flow handle that the follow-up +/// call to `auth/2fa/authenticate` must echo back. [availableFactors] lists +/// the supported factor ids ('totp', 'recovery_codes', 'webauthn') when the +/// server included them, so the UI can pick the right input affordance. +class MfaRequiredException implements Exception { + final String sessionToken; + final List availableFactors; + + const MfaRequiredException({required this.sessionToken, this.availableFactors = const []}); + + @override + String toString() => 'MfaRequiredException(factors: $availableFactors, sessionToken: )'; +} diff --git a/lib/database/powersync/tables/exercise.dart b/lib/database/powersync/tables/exercise.dart index 633d5a700..408bf457c 100644 --- a/lib/database/powersync/tables/exercise.dart +++ b/lib/database/powersync/tables/exercise.dart @@ -256,7 +256,7 @@ class ExerciseImageTable extends Table { DateTimeColumn get created => dateTime()(); DateTimeColumn get lastUpdate => dateTime().named('last_update')(); - // License (TASL — Title / Author / Source / License). license_author may be + // License (TASL, Title / Author / Source / License). license_author may be // null on the server (TextField with null=True); the others are not-null // strings (possibly empty) on the server. IntColumn get licenseId => integer().named('license_id')(); @@ -312,7 +312,7 @@ class ExerciseVideoTable extends Table { DateTimeColumn get created => dateTime()(); DateTimeColumn get lastUpdate => dateTime().named('last_update')(); - // License (TASL — Title / Author / Source / License). license_author may be + // License (TASL, Title / Author / Source / License). license_author may be // null on the server (TextField with null=True); the others are not-null // strings (possibly empty) on the server. IntColumn get licenseId => integer().named('license_id')(); diff --git a/lib/database/powersync/tables/nutrition.dart b/lib/database/powersync/tables/nutrition.dart index 78022cf3e..498b2ebae 100644 --- a/lib/database/powersync/tables/nutrition.dart +++ b/lib/database/powersync/tables/nutrition.dart @@ -134,7 +134,7 @@ const PowersyncMealTable = ps.Table( /// Identified by uuid client-side; the `meal_id` FK is the parent meal's /// uuid (not the server-side integer PK). `amount` is a /// `DecimalField(decimal_places=2, max_digits=6)` server-side, stored here -/// as REAL — the rounding happens implicitly when DRF coerces back. +/// as REAL, the rounding happens implicitly when DRF coerces back. @UseRowClass(MealItem, constructor: 'fromDrift') class MealItemTable extends Table { @override diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index b4bdc363e..a1fc335b5 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -59,7 +59,7 @@ const PREFS_USER_DARK_THEME = 'userDarkMode'; const PREFS_USER_LOCALE = 'userLocale'; const PREFS_LAST_SERVER = 'lastServer'; -/// Headless JWT auth — SharedPreferences keys. +/// Headless JWT auth: SharedPreferences keys. /// /// Read in parallel with the legacy `PREFS_USER` blob during the migration /// window; once a user logs in via the headless flow these supersede it. diff --git a/lib/helpers/jwt.dart b/lib/helpers/jwt.dart index 5cc9ed287..a03cb4fe8 100644 --- a/lib/helpers/jwt.dart +++ b/lib/helpers/jwt.dart @@ -26,8 +26,8 @@ final _logger = Logger('jwt'); /// /// Returns null when the input is not a three-segment token, when the middle /// segment is not valid base64-url, or when the decoded bytes are not a JSON -/// object. The signature is not verified — callers must treat the result as -/// untrusted data. +/// object. The signature is not verified, so callers must treat the result +/// as untrusted data. Map? decodeJwtPayload(String jwt) { try { final parts = jwt.split('.'); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 29adc4b1d..490e3183c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -56,17 +56,21 @@ "@invalidUsername": { "description": "Error message when the user enters an invalid username" }, - "useApiToken": "Use API Token", + "useRefreshToken": "Use refresh token", "useUsernameAndPassword": "Use username and password", - "apiToken": "API Token", - "@apiToken": {}, - "invalidApiToken": "Please enter a valid API key", - "@invalidApiToken": { - "description": "Error message when the user enters an invalid API key" + "refreshToken": "Refresh token", + "@refreshToken": {}, + "invalidRefreshToken": "Please enter a valid refresh token", + "@invalidRefreshToken": { + "description": "Error message when the user enters an invalid refresh token" }, - "apiTokenValidChars": "An API key may only contain the letters a-f, numbers 0-9 and be exactly 40 characters long", - "@apiTokenValidChars": { - "description": "Error message when the user tries to input a API key with forbidden characters" + "refreshTokenValidChars": "A refresh token has three dot-separated segments (header.payload.signature), each made of letters, digits, '-' and '_'", + "@refreshTokenValidChars": { + "description": "Error message when the user pastes a string that does not match the JWT shape" + }, + "refreshTokenHelperText": "Generate a JWT refresh token on the wger website and paste it here. Useful when your server sits behind an auth proxy or when you want to skip the regular login flow.", + "@refreshTokenHelperText": { + "description": "Helper text on the refresh-token paste field" }, "customServerUrl": "URL of the wger instance", "@customServerUrl": { diff --git a/lib/models/exercises/exercise_filters.dart b/lib/models/exercises/exercise_filters.dart index 3e842d840..8a5424a6c 100644 --- a/lib/models/exercises/exercise_filters.dart +++ b/lib/models/exercises/exercise_filters.dart @@ -44,7 +44,7 @@ class ExerciseFilters { /// Locale-aware default filter set. /// - /// In an English locale "current + English" collapses to "current" — there + /// In an English locale "current + English" collapses to "current", there /// is no extra fallback to add. Everywhere else, falling back to English is /// the default. All other fields take the constructor defaults. factory ExerciseFilters.defaultFor(String localeCode) => ExerciseFilters( diff --git a/lib/models/nutrition/ingredient.dart b/lib/models/nutrition/ingredient.dart index e6706110a..f6f6bbc48 100644 --- a/lib/models/nutrition/ingredient.dart +++ b/lib/models/nutrition/ingredient.dart @@ -159,7 +159,7 @@ class Ingredient { Map toJson() => _$IngredientToJson(this); NutritionalValues get nutritionalValues { - // Treat missing macronutrient data as zero — better to show "0 g + // Treat missing macronutrient data as zero, better to show "0 g // fiber" than to omit/explode for ingredients with sparse data. return NutritionalValues.values( energy * 1, diff --git a/lib/models/nutrition/ingredient_filters.dart b/lib/models/nutrition/ingredient_filters.dart index 8916cd6c4..d11801048 100644 --- a/lib/models/nutrition/ingredient_filters.dart +++ b/lib/models/nutrition/ingredient_filters.dart @@ -22,7 +22,7 @@ class IngredientFilters { /// Locale-aware default filter set. /// - /// In an English locale "current + English" collapses to "current" — there + /// In an English locale "current + English" collapses to "current", there /// is no extra fallback to add. Everywhere else, falling back to English is /// the default. All other fields take the constructor defaults. factory IngredientFilters.defaultFor(String localeCode) => IngredientFilters( diff --git a/lib/models/nutrition/ingredient_image.dart b/lib/models/nutrition/ingredient_image.dart index dd38cdcbd..9bafe09e5 100644 --- a/lib/models/nutrition/ingredient_image.dart +++ b/lib/models/nutrition/ingredient_image.dart @@ -62,7 +62,7 @@ class IngredientImage { @JsonKey(required: true, name: 'license') final int licenseId; - /// Author(s) — may be null on the server (`TextField(null=True)`) + /// Author(s), may be null on the server (`TextField(null=True)`) @JsonKey(required: true, name: 'license_author') final String? author; diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index 294d18f96..027eb3cdd 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -23,7 +23,7 @@ import 'package:wger/models/nutrition/ingredient_weight_unit.dart'; import 'package:wger/models/nutrition/meal_item.dart'; import 'package:wger/models/nutrition/nutritional_values.dart'; -/// Diary log entry — one ingredient consumed at a point in time. +/// Diary log entry, one ingredient consumed at a point in time. /// /// Lives entirely in PowerSync/Drift now: row IDs are client-generated UUIDs /// (so we can write before the server has assigned an integer PK), and the diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index 0668ada9c..eecaa93d7 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -26,7 +26,7 @@ class MealItem { /// Client-generated UUID, is `null` only before the first persist String? id; - /// FK to the parent meal — the meal's UUID, not the server-side integer PK. + /// FK to the parent meal, the meal's UUID, not the server-side integer PK. late String mealId; late int ingredientId; diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index 2b92792ef..ddaa2124e 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -64,7 +64,7 @@ class DjangoConnector extends PowerSyncBackendConnector { /// permanent-failure op would re-pop the dialog on every sync tick /// (PowerSync keeps re-driving `uploadData` until the transaction /// is completed, and our `transaction.complete()` only fires once - /// the loop finishes — so we'd see the dialog at every iteration). + /// the loop finishes, so we'd see the dialog at every iteration). /// Resets on app restart. final Set _reportedFailedOps = {}; @@ -222,7 +222,7 @@ class DjangoConnector extends PowerSyncBackendConnector { try { decoded = json.decode(response.body); } on FormatException { - // Non-JSON response on a 200 — uncommon but harmless to ignore. + // Non-JSON response on a 200, uncommon but harmless to ignore. return; } if (decoded is! Map || !decoded.containsKey('error')) { diff --git a/lib/providers/auth_http_client.dart b/lib/providers/auth_http_client.dart index 0d24216cb..cc5e89b40 100644 --- a/lib/providers/auth_http_client.dart +++ b/lib/providers/auth_http_client.dart @@ -39,7 +39,7 @@ const _refreshLeeway = Duration(seconds: 30); /// stored `accessExpiresAt` is within [_refreshLeeway] of now. /// - On a 401 reply for a *replayable* `http.Request` body, refresh once /// and retry. If the retry also returns 401, the user is logged out. -/// Non-replayable bodies (multipart / streamed) are not retried — the +/// Non-replayable bodies (multipart / streamed) are not retried; the /// pre-emptive refresh in the happy path is the primary safeguard. /// /// Wrapped behind [authenticatedHttpClientProvider] so consumers @@ -157,8 +157,8 @@ class AuthHttpClient extends http.BaseClient { /// Provider of the authenticated HTTP client used by every data-API call. /// Wraps the raw client from [authHttpClientProvider] (kept separate so the -/// notifier itself can issue unauthenticated requests — login, refresh, -/// version probe — without recursing through this wrapper). +/// notifier itself can issue unauthenticated requests (login, refresh, +/// version probe) without recursing through this wrapper). final authenticatedHttpClientProvider = Provider( (ref) => AuthHttpClient( inner: ref.watch(authHttpClientProvider), diff --git a/lib/providers/auth_notifier.dart b/lib/providers/auth_notifier.dart index dc8ff83fa..6fc91ac5b 100644 --- a/lib/providers/auth_notifier.dart +++ b/lib/providers/auth_notifier.dart @@ -28,6 +28,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:version/version.dart'; import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/mfa_required_exception.dart'; import 'package:wger/database/powersync/powersync.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/jwt.dart'; @@ -45,13 +46,12 @@ part 'auth_notifier.g.dart'; const MIN_APP_VERSION_URL = 'min-app-version'; const SERVER_VERSION_URL = 'version'; -const REGISTRATION_URL = 'register'; -const LOGIN_URL = 'login'; -const USERPROFILE_URL = 'userprofile'; -/// `allauth.headless` `app` client refresh endpoint, relative to the +/// `allauth.headless` `app` client endpoints, relative to the /// `/_allauth/app/v1/` base. const HEADLESS_TOKENS_REFRESH_PATH = 'tokens/refresh'; +const HEADLESS_AUTH_LOGIN_PATH = 'auth/login'; +const HEADLESS_AUTH_SIGNUP_PATH = 'auth/signup'; /// HTTP client used by the auth notifier. Override in tests. final authHttpClientProvider = Provider((ref) => http.Client()); @@ -72,7 +72,9 @@ class AuthNotifier extends _$AuthNotifier { return _tryAutoLogin(); } - /// Registers a new user and logs in. + /// Registers a new user and logs in via the `allauth.headless` signup + /// endpoint. The response already carries the access + refresh tokens, + /// so no separate login call is needed. Future register({ required String username, required String password, @@ -81,103 +83,180 @@ class AuthNotifier extends _$AuthNotifier { String locale = 'en', }) async { final appVersion = _currentOrBlank().applicationVersion ?? await PackageInfo.fromPlatform(); - final data = { - 'username': username, - 'password': password, - }; + final body = {'username': username, 'password': password}; if (email.isNotEmpty) { - data['email'] = email; + body['email'] = email; } + final response = await _client.post( - makeUri(serverUrl, REGISTRATION_URL), + makeHeadlessUri(serverUrl, HEADLESS_AUTH_SIGNUP_PATH), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(appVersion), HttpHeaders.acceptLanguageHeader: locale, }, - body: json.encode(data), + body: json.encode(body), ); - - if (response.statusCode >= 400) { - throw WgerHttpException(response); - } - - return login(username, password, serverUrl, null); + final creds = _consumeHeadlessAuthResponse(response); + return _completeLogin(creds, serverUrl, appVersion); } - /// Authenticates a user (by password or API token). + /// Authenticates a user. + /// + /// Two modes: + /// 1. [refreshToken] is non-empty → treated as a refresh token the user + /// minted on the wger website. Exchanged immediately for a fresh + /// access token via the `allauth.headless` `tokens/refresh` endpoint; + /// the rotated bundle is persisted as [AuthTokenType.headlessJwt]. + /// Useful when the server sits behind an auth proxy that breaks the + /// interactive login flow. + /// 2. Otherwise the `auth/login` endpoint is used with username + + /// password. A pending second-factor flow surfaces as + /// [MfaRequiredException] for the caller to route to the 2FA + /// challenge screen. Future login( String username, String password, String serverUrl, - String? apiToken, + String? refreshToken, ) async { final appVersion = _currentOrBlank().applicationVersion ?? await PackageInfo.fromPlatform(); - final String token; + final creds = await _obtainCredentials( + username, + password, + serverUrl, + refreshToken, + appVersion, + ); + return _completeLogin(creds, serverUrl, appVersion); + } - if (apiToken != null && apiToken.isNotEmpty) { - final response = await _client.get( - makeUri(serverUrl, USERPROFILE_URL), - headers: { - HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', - HttpHeaders.userAgentHeader: getAppNameHeader(appVersion), - HttpHeaders.authorizationHeader: 'Token $apiToken', - }, - ); - - if (response.statusCode >= 400) { - throw WgerHttpException(response); - } - token = apiToken; - } else { - final response = await _client.post( - makeUri(serverUrl, LOGIN_URL), - headers: { - HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8', - HttpHeaders.userAgentHeader: getAppNameHeader(appVersion), - }, - body: json.encode({'username': username, 'password': password}), - ); - - if (response.statusCode >= 400) { - throw WgerHttpException(response); - } - - token = json.decode(response.body)['token']; + Future<_FreshCredentials> _obtainCredentials( + String username, + String password, + String serverUrl, + String? pastedRefreshToken, + PackageInfo appVersion, + ) async { + if (pastedRefreshToken != null && pastedRefreshToken.isNotEmpty) { + return _exchangePastedRefreshToken(pastedRefreshToken, serverUrl, appVersion); } - // Persist login before the update-gate checks, matching legacy behavior. - final prefs = PreferenceHelper.asyncPref; - await prefs.setString( - PREFS_USER, - json.encode({'token': token, 'serverUrl': serverUrl}), - ); - await prefs.setString( - PREFS_LAST_SERVER, - json.encode({'serverUrl': serverUrl}), + final response = await _client.post( + makeHeadlessUri(serverUrl, HEADLESS_AUTH_LOGIN_PATH), + headers: { + HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8', + HttpHeaders.userAgentHeader: getAppNameHeader(appVersion), + }, + body: json.encode({'username': username, 'password': password}), ); + return _consumeHeadlessAuthResponse(response); + } - // Both branches above produce a legacy permanent DRF token; the headless - // JWT login path is added in a later step. - const tokenType = AuthTokenType.legacyApiToken; + /// Exchanges a manually-pasted refresh token for a fresh access + refresh + /// bundle. Rotation is on by default server-side, so the pasted token is + /// invalidated as part of this call and the new refresh token is what + /// ends up persisted in secure storage. Throws [WgerHttpException] when + /// the server rejects the pasted token. + Future<_FreshCredentials> _exchangePastedRefreshToken( + String refreshToken, + String serverUrl, + PackageInfo appVersion, + ) async { + final response = await _client.post( + makeHeadlessUri(serverUrl, HEADLESS_TOKENS_REFRESH_PATH), + headers: { + HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8', + HttpHeaders.userAgentHeader: getAppNameHeader(appVersion), + }, + body: json.encode({'refresh_token': refreshToken}), + ); + return _consumeHeadlessAuthResponse(response); + } + + /// Parses the standard `allauth.headless` auth response envelope. + /// + /// Returns a populated [_FreshCredentials] on 200 (tokens carried in + /// `meta`). + /// + /// Throws: + /// - [MfaRequiredException] on a 401 that carries `meta.session_token`, + /// signalling that the user must complete a second factor before tokens + /// are issued. + /// - [WgerHttpException] for any other status, or for malformed / partial + /// bodies on otherwise-successful responses. + _FreshCredentials _consumeHeadlessAuthResponse(http.Response response) { + final Map body; + try { + body = json.decode(response.body) as Map; + } catch (_) { + throw WgerHttpException(response); + } + + if (response.statusCode == 401) { + final meta = body['meta'] as Map?; + final sessionToken = meta?['session_token'] as String?; + if (sessionToken != null && sessionToken.isNotEmpty) { + final flows = (body['data'] as Map?)?['flows'] as List?; + final factors = + flows + ?.whereType>() + .where( + (f) => f['id'] == 'mfa_authenticate' && (f['is_pending'] as bool? ?? false), + ) + .expand((f) => (f['types'] as List?)?.cast() ?? const []) + .toList() ?? + const []; + throw MfaRequiredException(sessionToken: sessionToken, availableFactors: factors); + } + throw WgerHttpException(response); + } + + if (response.statusCode != 200) { + throw WgerHttpException(response); + } + + final meta = body['meta'] as Map?; + final accessToken = meta?['access_token'] as String?; + if (accessToken == null || accessToken.isEmpty) { + // 200 without tokens, likely a still-pending flow we don't know how + // to drive. Surface as an HTTP error so the caller renders something. + throw WgerHttpException(response); + } + return _FreshCredentials( + token: accessToken, + tokenType: AuthTokenType.headlessJwt, + refreshToken: meta?['refresh_token'] as String?, + accessExpiresAt: jwtExp(decodeJwtPayload(accessToken)), + ); + } + + /// Shared post-credentials path: persist the new bundle, run the gating + /// chain, swap PowerSync's connector if it was already up, invalidate the + /// data providers so they refetch with the new auth. + Future _completeLogin( + _FreshCredentials creds, + String serverUrl, + PackageInfo appVersion, + ) async { + await _persistCredentials(creds, serverUrl); var newState = await _resolveAuthState( - token: token, - tokenType: tokenType, + token: creds.token, + tokenType: creds.tokenType, serverUrl: serverUrl, appVersion: appVersion, + accessExpiresAt: creds.accessExpiresAt, ); if (newState.status == AuthStatus.loggedIn && - !await _serverConfigSane(serverUrl, token, tokenType)) { + !await _serverConfigSane(serverUrl, creds.token, creds.tokenType)) { newState = newState.copyWith(serverConfigWarning: true); } state = AsyncData(newState); if (newState.status == AuthStatus.loggedIn) { - // If PowerSync was already running from a previous session, swap its - // connector so it picks up the new user's credentials. await _reconnectPowerSyncIfBuilt(serverUrl); _invalidatePostLoginProviders(); } @@ -188,7 +267,40 @@ class AuthNotifier extends _$AuthNotifier { }; } - /// Clears the server config warning flag — called from the auth screen after + /// Writes a fresh credential bundle to disk and wipes the *other* token + /// format, so a re-login under a different mode (e.g. headless → API key) + /// does not leave stale credentials behind. + Future _persistCredentials(_FreshCredentials creds, String serverUrl) async { + final prefs = PreferenceHelper.asyncPref; + await prefs.setString(PREFS_LAST_SERVER, json.encode({'serverUrl': serverUrl})); + + switch (creds.tokenType) { + case AuthTokenType.legacyApiToken: + await prefs.setString( + PREFS_USER, + json.encode({'token': creds.token, 'serverUrl': serverUrl}), + ); + await _wipeStoredCredentials(AuthTokenType.headlessJwt); + case AuthTokenType.headlessJwt: + await prefs.setString(PREFS_ACCESS_TOKEN, creds.token); + if (creds.accessExpiresAt != null) { + await prefs.setInt( + PREFS_ACCESS_EXPIRES_AT, + creds.accessExpiresAt!.millisecondsSinceEpoch, + ); + } else { + await prefs.remove(PREFS_ACCESS_EXPIRES_AT); + } + await prefs.setString(PREFS_TOKEN_TYPE, AuthTokenType.headlessJwt.name); + await prefs.setString(PREFS_SERVER_URL, serverUrl); + if (creds.refreshToken != null) { + await ref.read(secureTokenStorageProvider).writeRefreshToken(creds.refreshToken!); + } + await _wipeStoredCredentials(AuthTokenType.legacyApiToken); + } + } + + /// Clears the server config warning flag, called from the auth screen after /// the corresponding warning dialog has been shown to the user, so it doesn't /// re-appear on the next state read. void clearServerConfigWarning() { @@ -544,7 +656,7 @@ class AuthNotifier extends _$AuthNotifier { /// /// Single-flight: concurrent callers share one HTTP request. On any /// failure (missing refresh token, missing serverUrl, network error, - /// non-200 response, malformed body) the user is logged out — there is + /// non-200 response, malformed body) the user is logged out. There is /// no usable session to fall back to once the refresh token is gone. /// /// On success: `state.accessToken` / `state.accessExpiresAt` are updated, @@ -768,9 +880,26 @@ bool _isNetworkError(Object e) { e is TimeoutException; } +/// In-memory credential bundle returned by the login / signup flows. The +/// `refreshToken` and `accessExpiresAt` fields are only populated for the +/// headless JWT path; the legacy DRF token path leaves them null. +class _FreshCredentials { + final String token; + final AuthTokenType tokenType; + final String? refreshToken; + final DateTime? accessExpiresAt; + + const _FreshCredentials({ + required this.token, + required this.tokenType, + this.refreshToken, + this.accessExpiresAt, + }); +} + /// Headless-JWT credential bundle as read from shared preferences during -/// auto-login. The refresh token is intentionally absent — it lives in -/// secure storage and is only fetched when a refresh actually runs. +/// auto-login. The refresh token is intentionally absent (it lives in +/// secure storage and is only fetched when a refresh actually runs). class _HeadlessAuthBundle { final String accessToken; final String serverUrl; diff --git a/lib/providers/auth_notifier.g.dart b/lib/providers/auth_notifier.g.dart index 24b5cf434..f60e6a2d9 100644 --- a/lib/providers/auth_notifier.g.dart +++ b/lib/providers/auth_notifier.g.dart @@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider AuthNotifier(); } -String _$authNotifierHash() => r'bf06472565bf8f94642b07465b74cd5997ea07dd'; +String _$authNotifierHash() => r'63224b401e551f1bd24d084d4c6c01e5e381ed35'; abstract class _$AuthNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/providers/exercise_filter_state.dart b/lib/providers/exercise_filter_state.dart index 363ebf296..d9cf433f0 100644 --- a/lib/providers/exercise_filter_state.dart +++ b/lib/providers/exercise_filter_state.dart @@ -22,7 +22,7 @@ import 'package:wger/models/exercises/exercise.dart'; /// UI state for the exercise list screen: the current filter /// configuration plus the resulting [filteredExercises]. The raw -/// equipment / categories lists are not kept here — consumers that +/// equipment / categories lists are not kept here, consumers that /// need them should watch [exerciseEquipmentProvider] / /// [exerciseCategoriesProvider] directly. class ExerciseFilterState { diff --git a/lib/providers/exercise_filters_riverpod.dart b/lib/providers/exercise_filters_riverpod.dart index 370ef1634..f9aa225ee 100644 --- a/lib/providers/exercise_filters_riverpod.dart +++ b/lib/providers/exercise_filters_riverpod.dart @@ -32,7 +32,7 @@ class ExerciseFiltersNotifier extends _$ExerciseFiltersNotifier { final prefs = PreferenceHelper.instance; final searchLanguage = await prefs.getExerciseSearchLanguage(); final searchMode = await prefs.getExerciseSearchMode(); - // Note: we don't persist selectedCategories — they reset on app restart. + // Note: we don't persist selectedCategories, they reset on app restart. return ExerciseFilters( searchLanguage: searchLanguage, searchMode: searchMode, @@ -77,7 +77,7 @@ class ExerciseFiltersNotifier extends _$ExerciseFiltersNotifier { } } -/// Synchronous unwrapper — to avoid AsyncValue boilerplate +/// Synchronous unwrapper, to avoid AsyncValue boilerplate final exerciseFiltersSyncProvider = Provider((ref) { return ref.watch(exerciseFiltersProvider).asData?.value ?? const ExerciseFilters(); }); diff --git a/lib/providers/exercise_repository.dart b/lib/providers/exercise_repository.dart index b487cdd66..dba865e2e 100644 --- a/lib/providers/exercise_repository.dart +++ b/lib/providers/exercise_repository.dart @@ -48,7 +48,7 @@ final exerciseRepositoryProvider = Provider((ref) { /// Read access for the exercise catalogue. /// /// The catalogue is denormalised across many tables (translations, muscles, -/// equipment, category, images, videos) — this repository owns the join + +/// equipment, category, images, videos), this repository owns the join + /// assembly so the [Exercises] notifier stays focused on state-shape and /// search routing, and so tests can swap a single mock instead of stubbing /// the whole `DriftPowersyncDatabase`. @@ -351,7 +351,7 @@ class ExerciseRepository { return _db.select(_db.muscleTable).watch(); } - /// Streams the list of supported languages — reference data for exercise + /// Streams the list of supported languages, reference data for exercise /// translations. Stream> watchLanguagesDrift() { return _db.select(_db.languageTable).watch(); diff --git a/lib/providers/gallery_notifier.dart b/lib/providers/gallery_notifier.dart index 53368aa2e..28d23d5ce 100644 --- a/lib/providers/gallery_notifier.dart +++ b/lib/providers/gallery_notifier.dart @@ -59,7 +59,7 @@ class GalleryNotifier extends _$GalleryNotifier { if (newPath != null) { image.imagePath = newPath; } - // [image] is a shared reference held by the synced list — the path + // [image] is a shared reference held by the synced list, the path // mutation above is visible immediately. Notify listeners so widgets // pick up the new image bytes. state = AsyncData(List.of(_current)); diff --git a/lib/providers/gallery_repository.dart b/lib/providers/gallery_repository.dart index a58f7f87f..84803bfee 100644 --- a/lib/providers/gallery_repository.dart +++ b/lib/providers/gallery_repository.dart @@ -40,7 +40,7 @@ final galleryRepositoryProvider = Provider((ref) { /// /// REST handles anything that involves the binary file (create, edit-with- /// new-file). Reads, metadata edits and deletes go through the local -/// PowerSync-backed Drift table — see [watchAllDrift], [editLocalDrift] +/// PowerSync-backed Drift table, see [watchAllDrift], [editLocalDrift] /// and [deleteLocalDrift]. class GalleryRepository { static const _galleryUrlPath = 'gallery'; diff --git a/lib/providers/gym_log_notifier.dart b/lib/providers/gym_log_notifier.dart index 054daf31e..769d852a7 100644 --- a/lib/providers/gym_log_notifier.dart +++ b/lib/providers/gym_log_notifier.dart @@ -36,7 +36,7 @@ class GymLogNotifier extends _$GymLogNotifier { } void setLog(Log log) { - // Clear the id so Drift mints a fresh UUID on insert — the source log + // Clear the id so Drift mints a fresh UUID on insert, the source log // is a template, the new state is a separate entry that will get its // own DB row. state = log.copyWith(date: clock.now())..id = null; diff --git a/lib/providers/helpers.dart b/lib/providers/helpers.dart index c5faec488..ff2765ccf 100644 --- a/lib/providers/helpers.dart +++ b/lib/providers/helpers.dart @@ -24,7 +24,7 @@ import 'package:flutter_riverpod/misc.dart' show ProviderListenable; /// Awaits the first value of [provider] by explicitly subscribing via /// [Ref.listen]. Use this in notifier methods (outside of `build()`) /// instead of `ref.read(streamProvider.future)`, which can hang -/// indefinitely if no other consumer is `ref.watch`-ing the provider — +/// indefinitely if no other consumer is `ref.watch`-ing the provider: /// Riverpod's internal subscription for `.future` doesn't always trigger /// the underlying stream's first emission in that scenario. /// @@ -115,7 +115,7 @@ Uri makeHeadlessUri(String serverUrl, String path) { /// detected once via the REST API), so deployments with a non-default /// `MEDIA_URL` or a CDN in front of the media files work transparently. /// When omitted, the function falls back to the assumption that media -/// is served from `/media/` — Django's default. +/// is served from `/media/`, Django's default. Uri? mediaUri(String serverUrl, String? relativePath, {String? absolutePrefix}) { if (relativePath == null || relativePath.isEmpty) { return null; diff --git a/lib/providers/ingredient_notifier.dart b/lib/providers/ingredient_notifier.dart index d216ca405..9464c3807 100644 --- a/lib/providers/ingredient_notifier.dart +++ b/lib/providers/ingredient_notifier.dart @@ -55,7 +55,7 @@ final class IngredientNotifier extends _$IngredientNotifier { /// returned immediately without a DB read. Simultaneous calls for the /// same id are deduplicated. The provider `state` is used only as a /// status signal (loading/done/error) and does not carry the Ingredient - /// itself — consumers should read the data from the notifier's cache. + /// itself, consumers should read the data from the notifier's cache. Future fetch(int id) async { _logger.finer('Fetching ingredient id: $id'); diff --git a/lib/providers/media_url_prefix_notifier.dart b/lib/providers/media_url_prefix_notifier.dart index cb83d31b7..5d306e0a2 100644 --- a/lib/providers/media_url_prefix_notifier.dart +++ b/lib/providers/media_url_prefix_notifier.dart @@ -30,7 +30,7 @@ import 'package:wger/providers/wger_base.dart'; part 'media_url_prefix_notifier.g.dart'; /// Marker from the `upload_to` field on the Django `Image` model. -/// Stable in practice — changing it would require a Django data +/// Stable in practice, changing it would require a Django data /// migration and break existing image references. const _exerciseImagesMarker = 'exercise-images/'; @@ -74,9 +74,9 @@ String? extractMediaPrefix(dynamic responseBody) { /// the first result's `image` URL. /// /// State semantics: -/// - `null` — not yet detected; consumers should fall back to the +/// - `null`, not yet detected; consumers should fall back to the /// default prefix -/// - non-null — full URL prefix +/// - non-null, full URL prefix /// /// Cleared on logout. @Riverpod(keepAlive: true) diff --git a/lib/providers/media_url_prefix_notifier.g.dart b/lib/providers/media_url_prefix_notifier.g.dart index cc4910583..a773319b7 100644 --- a/lib/providers/media_url_prefix_notifier.g.dart +++ b/lib/providers/media_url_prefix_notifier.g.dart @@ -18,9 +18,9 @@ part of 'media_url_prefix_notifier.dart'; /// the first result's `image` URL. /// /// State semantics: -/// - `null` — not yet detected; consumers should fall back to the +/// - `null`, not yet detected; consumers should fall back to the /// default prefix -/// - non-null — full URL prefix +/// - non-null, full URL prefix /// /// Cleared on logout. @@ -37,9 +37,9 @@ final mediaUrlPrefixProvider = MediaUrlPrefixNotifierProvider._(); /// the first result's `image` URL. /// /// State semantics: -/// - `null` — not yet detected; consumers should fall back to the +/// - `null`, not yet detected; consumers should fall back to the /// default prefix -/// - non-null — full URL prefix +/// - non-null, full URL prefix /// /// Cleared on logout. final class MediaUrlPrefixNotifierProvider @@ -54,9 +54,9 @@ final class MediaUrlPrefixNotifierProvider /// the first result's `image` URL. /// /// State semantics: - /// - `null` — not yet detected; consumers should fall back to the + /// - `null`, not yet detected; consumers should fall back to the /// default prefix - /// - non-null — full URL prefix + /// - non-null, full URL prefix /// /// Cleared on logout. MediaUrlPrefixNotifierProvider._() @@ -90,9 +90,9 @@ String _$mediaUrlPrefixNotifierHash() => r'a152afb08fc3ce66e92d9a7872010f84f4300 /// the first result's `image` URL. /// /// State semantics: -/// - `null` — not yet detected; consumers should fall back to the +/// - `null`, not yet detected; consumers should fall back to the /// default prefix -/// - non-null — full URL prefix +/// - non-null, full URL prefix /// /// Cleared on logout. diff --git a/lib/providers/routines_notifier.dart b/lib/providers/routines_notifier.dart index 31b62764e..b6975c8a6 100644 --- a/lib/providers/routines_notifier.dart +++ b/lib/providers/routines_notifier.dart @@ -97,10 +97,10 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { // Top-level routine list comes from PowerSync. Two kinds of sub-data are // layered on top: // - // * Plan structure (days, slots, set configs) — fetched via REST by + // * Plan structure (days, slots, set configs), fetched via REST by // [fetchAndSetRoutineFull]; we carry it forward from the previous // state on every stream emission so a remote edit doesn't wipe it. - // * Sessions + their logs (with `log.exerciseObj` hydrated) — pulled + // * Sessions + their logs (with `log.exerciseObj` hydrated), pulled // in from [workoutSessionProvider] / [exercisesProvider] below. final repo = ref.read(routinesRepositoryProvider); @@ -257,7 +257,7 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { _hydrateRoutine(routine); // Inject the hydrated routine into the current state. Note: this is - // a transient overlay — the next PowerSync stream tick re-emits the + // a transient overlay, the next PowerSync stream tick re-emits the // top-level routine (without sub-data), but `build()` re-attaches // sub-data from the previous state, so the hydration survives. final current = state.value ?? const RoutinesState(); @@ -387,7 +387,7 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { } /// Single-config write helper. Intentionally does NOT trigger a routine - /// refresh — the only caller (`SlotEntryForm._save`) batches several of + /// refresh, the only caller (`SlotEntryForm._save`) batches several of /// these in a `Future.wait` and then calls [editSlotEntry] right after, /// which performs the refresh once for the whole batch. Future handleConfig(SlotEntry entry, num? value, ConfigType type) async { diff --git a/lib/providers/routines_repository.dart b/lib/providers/routines_repository.dart index f104d984a..127a1b4ab 100644 --- a/lib/providers/routines_repository.dart +++ b/lib/providers/routines_repository.dart @@ -45,7 +45,7 @@ RoutinesRepository routinesRepository(Ref ref) { /// HTTP for everything that hasn't been migrated to PowerSync yet (creation /// of routines, days, slots, slot entries, configs, …). Top-level [Routine] /// reads as well as edit/delete go through the local PowerSync-backed Drift -/// table — see [watchAllDrift], [editLocalDrift], [deleteLocalDrift]. +/// table, see [watchAllDrift], [editLocalDrift], [deleteLocalDrift]. class RoutinesRepository { RoutinesRepository(this._baseProvider, this._db); @@ -122,7 +122,7 @@ class RoutinesRepository { /// /// Templates (`is_template = TRUE`, including public ones) are excluded at /// the sync-rule level (see `sync_rules.yaml`), so they never reach the - /// local DB — no client-side filter needed here. + /// local DB, no client-side filter needed here. /// /// Sort matches Django's `Routine.Meta.ordering = ['-start', '-created']` so /// that REST responses and PowerSync emissions agree on the row order. The diff --git a/lib/providers/wger_base.dart b/lib/providers/wger_base.dart index 6857acab9..376813556 100644 --- a/lib/providers/wger_base.dart +++ b/lib/providers/wger_base.dart @@ -27,7 +27,7 @@ import 'package:wger/providers/media_url_prefix_notifier.dart'; /// [AuthNotifier] state. Consumers read this to make authenticated HTTP /// requests. Rebuilds whenever the auth state changes. /// -/// Deliberately does *not* depend on [mediaUrlPrefixProvider] — that +/// Deliberately does *not* depend on [mediaUrlPrefixProvider], that /// would create a cycle, since the prefix notifier reads /// [wgerBaseProvider] when probing. Consumers that need the resolved /// media URL go through [mediaUrlBuilderProvider] instead. diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index 131480bb6..37461727f 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -19,8 +19,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:wger/core/error_dialogs.dart'; import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/mfa_required_exception.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -29,9 +29,9 @@ import 'package:wger/providers/auth_state.dart'; import 'package:wger/screens/update_app_screen.dart'; import 'package:wger/screens/update_server_screen.dart'; import 'package:wger/theme/theme.dart'; -import 'package:wger/widgets/auth/api_token_field.dart'; import 'package:wger/widgets/auth/email_field.dart'; import 'package:wger/widgets/auth/password_field.dart'; +import 'package:wger/widgets/auth/refresh_token_field.dart'; import 'package:wger/widgets/auth/server_field.dart'; import 'package:wger/widgets/auth/username_field.dart'; import 'package:wger/widgets/core/server_config_warning_dialog.dart'; @@ -123,7 +123,7 @@ class _AuthCardState extends ConsumerState { 'email': '', 'password': '', 'serverUrl': '', - 'apiToken': '', + 'refreshToken': '', }; var _isLoading = false; final _usernameController = TextEditingController(); @@ -133,7 +133,7 @@ class _AuthCardState extends ConsumerState { final _serverUrlController = TextEditingController( text: kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD, ); - final _apiTokenController = TextEditingController(); + final _refreshTokenController = TextEditingController(); @override void dispose() { @@ -142,7 +142,7 @@ class _AuthCardState extends ConsumerState { _password2Controller.dispose(); _emailController.dispose(); _serverUrlController.dispose(); - _apiTokenController.dispose(); + _refreshTokenController.dispose(); super.dispose(); } @@ -170,7 +170,7 @@ class _AuthCardState extends ConsumerState { void _resetTextfields() { _usernameController.clear(); _passwordController.clear(); - _apiTokenController.clear(); + _refreshTokenController.clear(); } void _submit(BuildContext context) async { @@ -191,7 +191,7 @@ class _AuthCardState extends ConsumerState { _authData['username']!, _authData['password']!, _authData['serverUrl']!, - _authData['apiToken'], + _authData['refreshToken'], ); // Register new user @@ -228,29 +228,33 @@ class _AuthCardState extends ConsumerState { ref.read(authProvider.notifier).clearServerConfigWarning(); } } + + if (context.mounted) { + setState(() { + _isLoading = false; + }); + } + } on MfaRequiredException { + // TODO: route to a dedicated 2FA challenge screen. For now show a + // friendly fallback in the existing error slot so users on 2FA-enabled + // accounts get a readable message instead of an unhandled exception. + if (context.mounted) { + setState(() { + errorMessage = FormHttpErrorsWidget( + WgerHttpException.fromMap({ + 'mfa_required': + 'Two-factor authentication is enabled for this account. ' + 'Please sign in via the website for now, native 2FA support is coming.', + }), + ); + }); + } } on WgerHttpException catch (error) { if (context.mounted) { setState(() { errorMessage = FormHttpErrorsWidget(error); }); } - } catch (error) { - // Login is inherently online, but surface an unreachable server as a - // friendly message instead of crashing to the red error screen. - if (isNetworkError(error) && context.mounted) { - setState(() { - errorMessage = Padding( - padding: const EdgeInsets.only(bottom: 10), - child: Text( - AppLocalizations.of(context).errorCouldNotConnectToServer, - textAlign: TextAlign.center, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - ); - }); - } else { - rethrow; - } } finally { if (mounted) { setState(() => _isLoading = false); @@ -349,9 +353,9 @@ class _AuthCardState extends ConsumerState { // Off-stage widgets are kept in the tree, otherwise the server URL // would not be saved to _authData if (_authMode == AuthMode.Login && !_useUsernameAndPassword) - ApiTokenField( - controller: _apiTokenController, - onSaved: (value) => _authData['apiToken'] = value!, + RefreshTokenField( + controller: _refreshTokenController, + onSaved: (value) => _authData['refreshToken'] = value!, ), Offstage( offstage: _hideCustomServer, @@ -368,12 +372,14 @@ class _AuthCardState extends ConsumerState { ), if (!_hideCustomServer) TextButton( - key: const ValueKey('toggleApiTokenButton'), + key: const ValueKey('toggleRefreshTokenButton'), onPressed: _authMode == AuthMode.Login ? () => setState(() => _useUsernameAndPassword = !_useUsernameAndPassword) : null, child: Text( - _useUsernameAndPassword ? i18n.useApiToken : i18n.useUsernameAndPassword, + _useUsernameAndPassword + ? i18n.useRefreshToken + : i18n.useUsernameAndPassword, ), ), diff --git a/lib/widgets/auth/api_token_field.dart b/lib/widgets/auth/refresh_token_field.dart similarity index 53% rename from lib/widgets/auth/api_token_field.dart rename to lib/widgets/auth/refresh_token_field.dart index 48bb2c0f1..62cb767da 100644 --- a/lib/widgets/auth/api_token_field.dart +++ b/lib/widgets/auth/refresh_token_field.dart @@ -2,21 +2,22 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -class ApiTokenField extends StatefulWidget { +/// Three dot-separated base64url segments: the standard JWT shape, which +/// covers the refresh tokens issued by `allauth.headless`. Permissive on +/// length so future format changes do not lock users out. +final RegExp _jwtShape = RegExp(r'^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$'); + +class RefreshTokenField extends StatefulWidget { final TextEditingController controller; final Function(String?) onSaved; - const ApiTokenField({ - required this.controller, - required this.onSaved, - super.key, - }); + const RefreshTokenField({required this.controller, required this.onSaved, super.key}); @override - State createState() => _ApiTokenFieldState(); + State createState() => _RefreshTokenFieldState(); } -class _ApiTokenFieldState extends State { +class _RefreshTokenFieldState extends State { bool isObscure = true; @override @@ -24,13 +25,12 @@ class _ApiTokenFieldState extends State { final i18n = AppLocalizations.of(context); return TextFormField( - key: const ValueKey('inputApiToken'), + key: const ValueKey('inputRefreshToken'), decoration: InputDecoration( - labelText: i18n.apiToken, - helperText: - 'Only needed when using an authentication proxy for the backend, please consult the documentation', + labelText: i18n.refreshToken, + helperText: i18n.refreshTokenHelperText, errorMaxLines: 2, - helperMaxLines: 2, + helperMaxLines: 3, prefixIcon: const Icon(Icons.password), suffixIcon: IconButton( icon: Icon(isObscure ? Icons.visibility_off : Icons.visibility), @@ -47,16 +47,14 @@ class _ApiTokenFieldState extends State { keyboardType: TextInputType.emailAddress, validator: (value) { if (value == null || value.isEmpty) { - return i18n.invalidApiToken; + return i18n.invalidRefreshToken; } - if (!RegExp(r'^[a-f0-9]{40}$').hasMatch(value)) { - return i18n.apiTokenValidChars; + if (!_jwtShape.hasMatch(value)) { + return i18n.refreshTokenValidChars; } return null; }, - inputFormatters: [ - FilteringTextInputFormatter.deny(RegExp(r'\s\b|\b\s')), - ], + inputFormatters: [FilteringTextInputFormatter.deny(RegExp(r'\s'))], onSaved: widget.onSaved, ); } diff --git a/lib/widgets/core/wger_image.dart b/lib/widgets/core/wger_image.dart index 7e18bcc72..a761b042a 100644 --- a/lib/widgets/core/wger_image.dart +++ b/lib/widgets/core/wger_image.dart @@ -31,7 +31,7 @@ import 'package:wger/widgets/core/progress_indicator.dart'; /// the [errorWidget] (or a default broken-image icon) is shown. /// /// [cacheWidth] / [cacheHeight] are passed to the underlying decoder -/// so the cached bytes are scaled to display size — use this for +/// so the cached bytes are scaled to display size, use this for /// avatars and thumbnails to avoid keeping multi-megapixel originals /// in the cache. Both are pixel values, not logical pixels. /// diff --git a/lib/widgets/dashboard/widgets/weight.dart b/lib/widgets/dashboard/widgets/weight.dart index 25452ad34..0be3e29c2 100644 --- a/lib/widgets/dashboard/widgets/weight.dart +++ b/lib/widgets/dashboard/widgets/weight.dart @@ -65,7 +65,7 @@ class DashboardWeightWidget extends ConsumerWidget { // Composite loading / error / data resolution. We need both providers // ready before we can render the chart (entries → series, profile → // unit). Treating them independently with a nested .when() is what gave - // us the eternal-spinner bug when fetchProfile() returned null — so we + // us the eternal-spinner bug when fetchProfile() returned null, so we // funnel everything through a single decision tree here. if (entriesAsync.isLoading || profileAsync.isLoading) { return _shell(context, const BoxedProgressIndicator()); @@ -84,7 +84,7 @@ class DashboardWeightWidget extends ConsumerWidget { } final profile = profileAsync.value; if (profile == null) { - // Loaded successfully but the API returned no profile — treat the same + // Loaded successfully but the API returned no profile, treat the same // way we treat a server error so the user isn't stuck on a spinner. return _shell(context, const StreamErrorIndicator('User profile is unavailable')); } diff --git a/lib/widgets/exercises/autocompleter.dart b/lib/widgets/exercises/autocompleter.dart index cc7e8f4d9..12a53e43d 100644 --- a/lib/widgets/exercises/autocompleter.dart +++ b/lib/widgets/exercises/autocompleter.dart @@ -143,14 +143,14 @@ class _ExerciseAutocompleterState extends ConsumerState { ); } - /// The filter icon button — shows an active-filter badge and opens + /// The filter icon button, shows an active-filter badge and opens /// [ExerciseFilterDialog] on tap. Widget _filterButton(BuildContext context) { final filters = ref.watch(exerciseFiltersSyncProvider); final languageCode = Localizations.localeOf(context).languageCode; // Auto-correct: in an English locale "current + English" collapses to - // "current" — fix it once if a stored preference landed on the + // "current", fix it once if a stored preference landed on the // non-locale-aware default. if (languageCode == LANGUAGE_SHORT_ENGLISH && filters.searchLanguage == SearchLanguage.currentAndEnglish) { diff --git a/lib/widgets/exercises/images.dart b/lib/widgets/exercises/images.dart index 1a218e026..ca0bae135 100644 --- a/lib/widgets/exercises/images.dart +++ b/lib/widgets/exercises/images.dart @@ -42,7 +42,7 @@ class ExerciseImageWidget extends StatelessWidget { return WgerImage( mediaPath: image?.image, height: height, - // No width — let the parent decide, matching the previous Image.network + // No width, let the parent decide, matching the previous Image.network // behaviour where the natural aspect ratio drove sizing. fit: BoxFit.contain, errorWidget: _placeholder, diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index cbadc1e62..05edec215 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -101,7 +101,7 @@ Widget getMealItemForm( bool? test, ]) { return IngredientForm( - // The recent list is ephemeral display data — planId isn't used for + // The recent list is ephemeral display data, planId isn't used for // persistence, so an empty sentinel is fine. recent: recent.map((e) => LogItem.fromMealItem(e, '', e.mealId)).toList(), onSave: (BuildContext context, WidgetRef ref, MealItem mealItem, DateTime? dt) { diff --git a/lib/widgets/nutrition/ingredient_dialogs.dart b/lib/widgets/nutrition/ingredient_dialogs.dart index 0d9f9ba38..32f9d8719 100644 --- a/lib/widgets/nutrition/ingredient_dialogs.dart +++ b/lib/widgets/nutrition/ingredient_dialogs.dart @@ -191,7 +191,7 @@ class IngredientScanResultDialog extends StatelessWidget { final ingredient = snapshot.data; - // No product matched the barcode — offer the user to add it to OFF. + // No product matched the barcode, offer the user to add it to OFF. if (ingredient == null) { return AlertDialog( key: const Key('ingredient-scan-result-dialog'), @@ -222,7 +222,7 @@ class IngredientScanResultDialog extends StatelessWidget { ); } - // Product found — render details + confirm button. + // Product found, render details + confirm button. final goals = ingredient.nutritionalValues.toGoals(); final source = ingredient.sourceName ?? 'unknown'; return AlertDialog( diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index c2ebf0717..470200536 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -249,7 +249,7 @@ class MealItemEditableFullTile extends ConsumerWidget { tooltip: i18n.delete, iconSize: ICON_SIZE_SMALL, onPressed: () { - // Delete the meal item — goes through PowerSync, so offline is fine. + // Delete the meal item, goes through PowerSync, so offline is fine. ref.read(nutritionProvider.notifier).deleteMealItem(_item); // and inform the user diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index 4bf0d08c0..8a28c9151 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -57,7 +57,7 @@ class NutritionalPlansList extends riverpod.ConsumerWidget { final Color weightChangeColor; final profile = ref.watch(userProfileProvider).value; if (profile == null) { - // Profile not yet loaded — skip the weight-change row entirely. The + // Profile not yet loaded, skip the weight-change row entirely. The // widget will rebuild with the value once available. return const SizedBox.shrink(); } diff --git a/lib/widgets/nutrition/widgets.dart b/lib/widgets/nutrition/widgets.dart index 65998bafa..10463213c 100644 --- a/lib/widgets/nutrition/widgets.dart +++ b/lib/widgets/nutrition/widgets.dart @@ -274,14 +274,14 @@ class _IngredientTypeaheadState extends ConsumerState { ); } - /// The filter icon button — shows an active-filter badge and opens + /// The filter icon button, shows an active-filter badge and opens /// [IngredientFilterDialog] on tap. Widget filterButton() { final filters = ref.watch(ingredientFiltersSyncProvider); final languageCode = Localizations.localeOf(context).languageCode; // Auto-correct: in an English locale "current + English" collapses to - // "current" — fix it once if a stored preference landed on the + // "current", fix it once if a stored preference landed on the // non-locale-aware default. if (languageCode == LANGUAGE_SHORT_ENGLISH && filters.searchLanguage == SearchLanguage.currentAndEnglish) { diff --git a/lib/widgets/routines/forms/repetitions.dart b/lib/widgets/routines/forms/repetitions.dart index ea72ea9c0..56bce9e96 100644 --- a/lib/widgets/routines/forms/repetitions.dart +++ b/lib/widgets/routines/forms/repetitions.dart @@ -133,7 +133,7 @@ class _RepetitionInputWidgetState extends ConsumerState { } // Setting `controller.text` notifies its listeners synchronously, // which in turn calls `setState` on the surrounding Form/TextField - // state — and `didUpdateWidget` runs *during* the build cycle, so + // state, and `didUpdateWidget` runs *during* the build cycle, so // that's illegal. Defer the assignment to after the current frame. final text = widget.value == null ? '' : _numberFormat.format(widget.value); WidgetsBinding.instance.addPostFrameCallback((_) { diff --git a/lib/widgets/routines/forms/weight.dart b/lib/widgets/routines/forms/weight.dart index 8a9087457..34aeff6d1 100644 --- a/lib/widgets/routines/forms/weight.dart +++ b/lib/widgets/routines/forms/weight.dart @@ -130,7 +130,7 @@ class _WeightInputWidgetState extends ConsumerState { } // Setting `controller.text` notifies its listeners synchronously, // which in turn calls `setState` on the surrounding Form/TextField - // state — and `didUpdateWidget` runs *during* the build cycle, so + // state, and `didUpdateWidget` runs *during* the build cycle, so // that's illegal. Defer the assignment to after the current frame. final text = widget.value == null ? '' : _numberFormat.format(widget.value); WidgetsBinding.instance.addPostFrameCallback((_) { diff --git a/lib/widgets/search/language_dropdown.dart b/lib/widgets/search/language_dropdown.dart index 9a1090d71..bab1ef856 100644 --- a/lib/widgets/search/language_dropdown.dart +++ b/lib/widgets/search/language_dropdown.dart @@ -24,7 +24,7 @@ import 'package:wger/models/core/search_options.dart'; /// Dropdown that lets the user pick which language(s) to search in. /// /// Shared between exercise and ingredient search filters. The widget is -/// purely presentational — the caller passes the currently [selected] value +/// purely presentational, the caller passes the currently [selected] value /// and an [onChanged] callback to react to user input. class SearchLanguageDropdown extends StatelessWidget { final SearchLanguage selected; diff --git a/test/auth/auth_notifier_login_test.dart b/test/auth/auth_notifier_login_test.dart new file mode 100644 index 000000000..281107f49 --- /dev/null +++ b/test/auth/auth_notifier_login_test.dart @@ -0,0 +1,370 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:convert'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/http.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/mfa_required_exception.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/shared_preferences.dart'; +import 'package:wger/providers/auth_notifier.dart'; +import 'package:wger/providers/auth_state.dart'; +import 'package:wger/providers/secure_token_storage.dart'; + +import 'auth_notifier_login_test.mocks.dart'; + +@GenerateMocks([http.Client, SecureTokenStorage]) +void main() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + + late MockClient mockClient; + late MockSecureTokenStorage mockSecureStorage; + + const serverUrl = 'https://wger.example'; + const username = 'alice'; + const password = 'hunter2'; + const powerSyncUrl = 'https://ps.example/'; + + final tHeadlessLogin = Uri.parse('$serverUrl/_allauth/app/v1/auth/login'); + final tHeadlessSignup = Uri.parse('$serverUrl/_allauth/app/v1/auth/signup'); + final tVersion = Uri.parse('$serverUrl/api/v2/version/'); + final tMinAppVersion = Uri.parse('$serverUrl/api/v2/min-app-version/'); + final tPowerSyncToken = Uri.parse('$serverUrl/api/v2/powersync-token'); + final tLiveness = Uri.parse('${powerSyncUrl}probes/liveness'); + + /// Builds a JWT-shaped string with the given payload. Signature is a sham, + /// we only decode the middle segment. + String makeJwt(Map payload) { + String enc(Map m) => + base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', ''); + return '${enc({'alg': 'HS256', 'typ': 'JWT'})}.${enc(payload)}.signature'; + } + + ProviderContainer makeContainer() { + final c = ProviderContainer( + overrides: [ + authHttpClientProvider.overrideWithValue(mockClient), + secureTokenStorageProvider.overrideWithValue(mockSecureStorage), + ], + ); + addTearDown(c.dispose); + return c; + } + + setUp(() async { + mockClient = MockClient(); + mockSecureStorage = MockSecureTokenStorage(); + when(mockSecureStorage.deleteRefreshToken()).thenAnswer((_) async {}); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => null); + when(mockSecureStorage.writeRefreshToken(any)).thenAnswer((_) async {}); + + SharedPreferences.setMockInitialValues({}); + PackageInfo.setMockInitialValues( + appName: 'wger', + packageName: 'com.example.example', + version: '1.2.3', + buildNumber: '2', + buildSignature: 'buildSignature', + ); + await PreferenceHelper.asyncPref.clear(); + + // Default gating-chain mocks (happy path). Login-flow tests override + // only what they care about. + when(mockClient.get(tVersion)).thenAnswer((_) async => Response('"99.99.99"', 200)); + when(mockClient.get(tMinAppVersion)).thenAnswer((_) async => Response('"0.0.1"', 200)); + when( + mockClient.get(tPowerSyncToken, headers: anyNamed('headers')), + ).thenAnswer( + (_) async => Response( + jsonEncode({'token': 'ps-jwt', 'powersync_url': powerSyncUrl}), + 200, + ), + ); + when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200)); + // _serverConfigSane probe → null `next` means clean. + when( + mockClient.get(any, headers: anyNamed('headers')), + ).thenAnswer((_) async => Response(jsonEncode({'next': null}), 200)); + // Re-stub the explicit ones (any-match above otherwise wins). + when(mockClient.get(tVersion)).thenAnswer((_) async => Response('"99.99.99"', 200)); + when(mockClient.get(tMinAppVersion)).thenAnswer((_) async => Response('"0.0.1"', 200)); + when( + mockClient.get(tPowerSyncToken, headers: anyNamed('headers')), + ).thenAnswer( + (_) async => Response( + jsonEncode({'token': 'ps-jwt', 'powersync_url': powerSyncUrl}), + 200, + ), + ); + when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200)); + }); + + group('login: headless happy path', () { + test('200 → stores headless JWT bundle, wipes legacy PREFS_USER, state has tokens', () async { + final accessJwt = makeJwt({'sub': '7', 'exp': 1900000000}); + when( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': accessJwt, 'refresh_token': 'fresh-refresh'}, + }), + 200, + ), + ); + + final container = makeContainer(); + // Let auto-login settle as logged-out (no PREFS_USER yet). + await container.read(authProvider.future); + + // Seed a stale legacy blob *after* auto-login, so we can assert + // login() wipes it on success without auto-login itself trying to + // probe with it. + await PreferenceHelper.asyncPref.setString( + PREFS_USER, + jsonEncode({'token': 'stale-legacy', 'serverUrl': serverUrl}), + ); + + final result = await container + .read(authProvider.notifier) + .login(username, password, serverUrl, null); + + expect(result, LoginActions.proceed); + final state = container.read(authProvider).value!; + expect(state.tokenType, AuthTokenType.headlessJwt); + expect(state.accessToken, accessJwt); + expect(state.token, isNull); + expect(state.status, AuthStatus.loggedIn); + + // Refresh token in secure storage. + verify(mockSecureStorage.writeRefreshToken('fresh-refresh')).called(1); + + // Headless prefs populated. + final prefs = PreferenceHelper.asyncPref; + expect(await prefs.getString(PREFS_ACCESS_TOKEN), accessJwt); + expect(await prefs.getString(PREFS_TOKEN_TYPE), AuthTokenType.headlessJwt.name); + expect(await prefs.getString(PREFS_SERVER_URL), serverUrl); + + // Stale legacy blob wiped. + expect(await prefs.containsKey(PREFS_USER), false); + }); + + test('Authorization is not built by the notifier itself; the auth client owns it', () async { + final accessJwt = makeJwt({'exp': 1900000000}); + when( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': accessJwt, 'refresh_token': 'r'}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + await container.read(authProvider.notifier).login(username, password, serverUrl, null); + + // The headless login POST is unauthenticated (no Authorization header). + final captured = + verify( + mockClient.post( + tHeadlessLogin, + headers: captureAnyNamed('headers'), + body: anyNamed('body'), + ), + ).captured.last + as Map; + expect(captured.containsKey('authorization'), false); + }); + }); + + group('login: headless 401 / MFA detection', () { + test( + '401 with `meta.session_token` + `mfa_authenticate` flow → MfaRequiredException', + () async { + when( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 401, + 'data': { + 'flows': [ + { + 'id': 'mfa_authenticate', + 'is_pending': true, + 'types': ['totp', 'recovery_codes'], + }, + ], + }, + 'meta': {'session_token': 'flow-handle-xyz', 'is_authenticated': false}, + }), + 401, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + + try { + await container.read(authProvider.notifier).login(username, password, serverUrl, null); + fail('expected MfaRequiredException'); + } on MfaRequiredException catch (e) { + expect(e.sessionToken, 'flow-handle-xyz'); + expect(e.availableFactors, ['totp', 'recovery_codes']); + } + }, + ); + + test('plain 401 (no session_token) → WgerHttpException', () async { + when( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 401, + 'data': {}, + 'meta': {'is_authenticated': false}, + }), + 401, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + + expect( + container.read(authProvider.notifier).login(username, password, serverUrl, null), + throwsA(isA()), + ); + }); + }); + + group('login: pasted refresh token', () { + final tRefresh = Uri.parse('$serverUrl/_allauth/app/v1/tokens/refresh'); + + test('exchanges at tokens/refresh and stores the rotated bundle', () async { + final newAccess = makeJwt({'exp': 1900000000}); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': newAccess, 'refresh_token': 'rotated-refresh'}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + + final result = await container + .read(authProvider.notifier) + .login('', '', serverUrl, 'pasted-refresh-token'); + + expect(result, LoginActions.proceed); + final state = container.read(authProvider).value!; + expect(state.tokenType, AuthTokenType.headlessJwt); + expect(state.accessToken, newAccess); + + verify(mockSecureStorage.writeRefreshToken('rotated-refresh')).called(1); + // Must not have hit the username/password endpoint. + verifyNever( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ); + // The pasted refresh token is sent as the body of the exchange call. + final captured = + verify( + mockClient.post( + tRefresh, + headers: anyNamed('headers'), + body: captureAnyNamed('body'), + ), + ).captured.single + as String; + expect(jsonDecode(captured)['refresh_token'], 'pasted-refresh-token'); + }); + + test('server rejection surfaces as WgerHttpException', () async { + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) async => Response(jsonEncode({'detail': 'invalid'}), 401)); + + final container = makeContainer(); + await container.read(authProvider.future); + + expect( + container.read(authProvider.notifier).login('', '', serverUrl, 'bad-refresh-token'), + throwsA(isA()), + ); + }); + }); + + group('register: headless signup', () { + test('200 stores tokens directly without a follow-up login call', () async { + final accessJwt = makeJwt({'exp': 1900000000}); + when( + mockClient.post(tHeadlessSignup, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) async => Response( + jsonEncode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': accessJwt, 'refresh_token': 'r'}, + }), + 200, + ), + ); + + final container = makeContainer(); + await container.read(authProvider.future); + + final result = await container + .read(authProvider.notifier) + .register( + username: username, + password: password, + email: 'alice@example.com', + serverUrl: serverUrl, + ); + + expect(result, LoginActions.proceed); + expect(container.read(authProvider).value!.tokenType, AuthTokenType.headlessJwt); + verify(mockSecureStorage.writeRefreshToken('r')).called(1); + }); + }); +} diff --git a/test/auth/auth_notifier_login_test.mocks.dart b/test/auth/auth_notifier_login_test.mocks.dart new file mode 100644 index 000000000..e0e36b7b1 --- /dev/null +++ b/test/auth/auth_notifier_login_test.mocks.dart @@ -0,0 +1,254 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/auth/auth_notifier_login_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; +import 'dart:convert' as _i4; +import 'dart:typed_data' as _i6; + +import 'package:http/http.dart' as _i2; +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i5; +import 'package:wger/providers/secure_token_storage.dart' as _i7; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { + _FakeStreamedResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [Client]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockClient extends _i1.Mock implements _i2.Client { + MockClient() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future<_i2.Response> head(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#head, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> get(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#get, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> post( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> put( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> patch( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> delete( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future read(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i3.Future.value( + _i5.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future); + + @override + _i3.Future<_i6.Uint8List> readBytes( + Uri? url, { + Map? headers, + }) => + (super.noSuchMethod( + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), + ) + as _i3.Future<_i6.Uint8List>); + + @override + _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => + (super.noSuchMethod( + Invocation.method(#send, [request]), + returnValue: _i3.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_1( + this, + Invocation.method(#send, [request]), + ), + ), + ) + as _i3.Future<_i2.StreamedResponse>); + + @override + void close() => super.noSuchMethod( + Invocation.method(#close, []), + returnValueForMissingStub: null, + ); +} + +/// A class which mocks [SecureTokenStorage]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockSecureTokenStorage extends _i1.Mock implements _i7.SecureTokenStorage { + MockSecureTokenStorage() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future writeRefreshToken(String? token) => + (super.noSuchMethod( + Invocation.method(#writeRefreshToken, [token]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future readRefreshToken() => + (super.noSuchMethod( + Invocation.method(#readRefreshToken, []), + returnValue: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteRefreshToken() => + (super.noSuchMethod( + Invocation.method(#deleteRefreshToken, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/auth/auth_notifier_powersync_test.dart b/test/auth/auth_notifier_powersync_test.dart index 4d295bbdf..02eec1498 100644 --- a/test/auth/auth_notifier_powersync_test.dart +++ b/test/auth/auth_notifier_powersync_test.dart @@ -440,7 +440,7 @@ void main() { final prefs = PreferenceHelper.asyncPref; await prefs.remove(PREFS_USER); await prefs.setString(PREFS_ACCESS_TOKEN, accessToken); - // Far in the future so we don't trip on expiry — refresh isn't wired yet. + // Far in the future so we don't trip on expiry, refresh isn't wired yet. await prefs.setInt( PREFS_ACCESS_EXPIRES_AT, DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch, @@ -450,7 +450,7 @@ void main() { } test('prefers the headless bundle over PREFS_USER and probes with Bearer', () async { - // Both formats present — headless must win. + // Both formats present, headless must win. await seedHeadlessBundle(accessToken: 'jwt-access'); await PreferenceHelper.asyncPref.setString( PREFS_USER, diff --git a/test/auth/auth_notifier_test.dart b/test/auth/auth_notifier_test.dart index 3f72c2bb0..b540406ce 100644 --- a/test/auth/auth_notifier_test.dart +++ b/test/auth/auth_notifier_test.dart @@ -28,47 +28,47 @@ void main() { const atMin = MIN_SERVER_VERSION; final belowMin = Version(minVersion.major, minVersion.minor - 1, 0).toString(); - test('server version greater than min — no update needed', () { + test('server version greater than min, no update needed', () { expect(serverUpdateRequired(aboveMin), false); }); - test('server version equal to min — no update needed', () { + test('server version equal to min, no update needed', () { expect(serverUpdateRequired(atMin), false); }); - test('server version less than min — update needed', () { + test('server version less than min, update needed', () { expect(serverUpdateRequired(belowMin), true); }); - test('server version with patch component less than min — update needed', () { + test('server version with patch component less than min, update needed', () { expect(serverUpdateRequired('$belowMin.9'), true); }); - test('server version with patch component greater than min — no update needed', () { + test('server version with patch component greater than min, no update needed', () { expect(serverUpdateRequired('$atMin.1'), false); }); - test('null server version — returns false (lenient, no lockout)', () { + test('null server version, returns false (lenient, no lockout)', () { expect(serverUpdateRequired(null), false); }); - test('server version with pre-release suffix — still parsed correctly', () { + test('server version with pre-release suffix, still parsed correctly', () { expect(serverUpdateRequired('$aboveMin.0-beta'), false); }); - test('server version with Python alpha suffix (e.g. 1.2.3.0a2) — parsed correctly', () { + test('server version with Python alpha suffix (e.g. 1.2.3.0a2), parsed correctly', () { expect(serverUpdateRequired('$aboveMin.0a2'), false); }); - test('server version with Python alpha suffix below min — blocked', () { + test('server version with Python alpha suffix below min, blocked', () { expect(serverUpdateRequired('$belowMin.0a2'), true); }); - test('server version with build metadata suffix — still parsed correctly', () { + test('server version with build metadata suffix, still parsed correctly', () { expect(serverUpdateRequired('$belowMin.0 (git-abc1234)'), true); }); - test('completely unparseable server version — returns false (lenient)', () { + test('completely unparseable server version, returns false (lenient)', () { expect(serverUpdateRequired('unknown'), false); }); }); diff --git a/test/auth/auth_screen_test.dart b/test/auth/auth_screen_test.dart index 180cc12ec..f4fc3f83b 100644 --- a/test/auth/auth_screen_test.dart +++ b/test/auth/auth_screen_test.dart @@ -31,44 +31,54 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/auth_notifier.dart'; +import 'package:wger/providers/secure_token_storage.dart'; import 'package:wger/screens/auth_screen.dart'; import 'auth_screen_test.mocks.dart'; -@GenerateMocks([http.Client]) +@GenerateMocks([http.Client, SecureTokenStorage]) void main() { /// Replacement for SharedPreferences.setMockInitialValues() SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); late MockClient mockClient; + late MockSecureTokenStorage mockSecureStorage; - final Uri tRegistration = Uri( + final Uri tHeadlessLogin = Uri( scheme: 'https', host: 'wger.de', - path: 'api/v2/register/', + path: '/_allauth/app/v1/auth/login', ); - - final Uri tLogin = Uri( + final Uri tHeadlessSignup = Uri( scheme: 'https', host: 'wger.de', - path: 'api/v2/login/', + path: '/_allauth/app/v1/auth/signup', ); - final Uri tProfileCheck = Uri( + final Uri tHeadlessRefresh = Uri( scheme: 'https', host: 'wger.de', - path: 'api/v2/userprofile/', + path: '/_allauth/app/v1/tokens/refresh', ); - final responseLoginOk = {'token': '1234567890abcdef1234567890abcdef12345678'}; - final responseRegistrationOk = { - 'message': 'api user successfully registered', - 'token': '1234567890abcdef1234567890abcdef12345678', + const validJwt = 'header.payload.signature'; + const otherJwt = 'header2.payload2.signature2'; + + /// Headless envelope carrying a sham JWT. The signature segment is not + /// validated client-side, so any three-dot string works. + Map headlessAuthOk() => { + 'status': 200, + 'data': {}, + 'meta': { + 'access_token': 'header.payload.signature', + 'refresh_token': 'refresh-token-${DateTime.now().microsecondsSinceEpoch}', + }, }; Widget getWidget() { return ProviderScope( overrides: [ authHttpClientProvider.overrideWithValue(mockClient), + secureTokenStorageProvider.overrideWithValue(mockSecureStorage), ], child: const MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -81,6 +91,10 @@ void main() { setUp(() { mockClient = MockClient(); + mockSecureStorage = MockSecureTokenStorage(); + when(mockSecureStorage.deleteRefreshToken()).thenAnswer((_) async {}); + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => null); + when(mockSecureStorage.writeRefreshToken(any)).thenAnswer((_) async {}); SharedPreferences.setMockInitialValues({}); PackageInfo.setMockInitialValues( @@ -91,26 +105,27 @@ void main() { buildSignature: 'buildSignature', ); + // Happy-path stubs for the headless login / signup endpoints; tests + // that exercise error responses override these as needed. when( mockClient.post( - tLogin, + tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body'), ), - ).thenAnswer((_) => Future(() => Response(json.encode(responseLoginOk), 200))); + ).thenAnswer((_) => Future(() => Response(json.encode(headlessAuthOk()), 200))); + when( + mockClient.post( + tHeadlessSignup, + headers: anyNamed('headers'), + body: anyNamed('body'), + ), + ).thenAnswer((_) => Future(() => Response(json.encode(headlessAuthOk()), 200))); when(mockClient.get(any)).thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200))); when( mockClient.get(any, headers: anyNamed('headers')), ).thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200))); - - when( - mockClient.post( - tRegistration, - headers: anyNamed('headers'), - body: anyNamed('body'), - ), - ).thenAnswer((_) => Future(() => Response(json.encode(responseRegistrationOk), 201))); }); group('Login mode', () { @@ -133,7 +148,7 @@ void main() { expect(find.byKey(const Key('actionButton')), findsOneWidget); expect(find.byKey(const Key('toggleActionButton')), findsOneWidget); expect(find.byKey(const Key('toggleCustomServerButton')), findsOneWidget); - expect(find.byKey(const ValueKey('toggleApiTokenButton')), findsNothing); + expect(find.byKey(const ValueKey('toggleRefreshTokenButton')), findsNothing); }); testWidgets('Login - with username & password - happy path', (WidgetTester tester) async { @@ -148,12 +163,12 @@ void main() { await tester.pumpAndSettle(); // Assert - expect(find.byKey(const ValueKey('inputApiToken')), findsNothing); + expect(find.byKey(const ValueKey('inputRefreshToken')), findsNothing); expect(find.textContaining('An Error Occurred'), findsNothing); verify(mockClient.get(any)); verify( mockClient.post( - tLogin, + tHeadlessLogin, headers: anyNamed('headers'), body: json.encode({'username': 'testuser', 'password': '123456789'}), ), @@ -169,7 +184,7 @@ void main() { }; when( mockClient.post( - tLogin, + tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body'), ), @@ -189,30 +204,41 @@ void main() { expect(find.textContaining('Username or password unknown'), findsOne); verify( mockClient.post( - tLogin, + tHeadlessLogin, headers: anyNamed('headers'), body: json.encode({'username': 'testuser', 'password': '123456789'}), ), ); }); - testWidgets('Login - with API token - happy path', (WidgetTester tester) async { - // Arrange + testWidgets('Login - with refresh token - happy path', (WidgetTester tester) async { + // Arrange: stub tokens/refresh to return a rotated bundle. + when( + mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer( + (_) => Future( + () => Response( + json.encode({ + 'status': 200, + 'data': {}, + 'meta': {'access_token': otherJwt, 'refresh_token': 'rotated'}, + }), + 200, + ), + ), + ); await tester.pumpWidget(getWidget()); await tester.pumpAndSettle(); // Act await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton'))); await tester.pump(); - await tester.tap(find.byKey(const ValueKey('toggleApiTokenButton'))); + await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton'))); await tester.pump(); - await tester.enterText( - find.byKey(const ValueKey('inputApiToken')), - '1234567890abcdef1234567890abcdef12345678', - ); + await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt); - // Assert that API token mode is active before submitting. - expect(find.byKey(const ValueKey('inputApiToken')), findsOne); + // Assert that refresh-token mode is active before submitting. + expect(find.byKey(const ValueKey('inputRefreshToken')), findsOne); expect(find.byKey(const Key('inputUsername')), findsNothing); expect(find.byKey(const Key('inputPassword')), findsNothing); @@ -222,48 +248,40 @@ void main() { // Assert expect(find.textContaining('An Error Occurred'), findsNothing); - verify( - mockClient.get( - tProfileCheck, - headers: argThat( - predicate( - (headers) => - headers is Map && - headers['authorization'] == 'Token 1234567890abcdef1234567890abcdef12345678', - ), - named: 'headers', - ), - ), - ); + // The pasted token is sent in the body of tokens/refresh. + final captured = + verify( + mockClient.post( + tHeadlessRefresh, + headers: anyNamed('headers'), + body: captureAnyNamed('body'), + ), + ).captured.single + as String; + expect(json.decode(captured)['refresh_token'], validJwt); + // The username/password endpoint must not be hit. verifyNever( - mockClient.post( - any, - headers: anyNamed('headers'), - body: anyNamed('body'), - ), + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), ); }); - testWidgets('Login - with API token - wrong key', (WidgetTester tester) async { + testWidgets('Login - with refresh token - server rejects it', (WidgetTester tester) async { // Arrange final response = { 'detail': ['Invalid token'], }; when( - mockClient.get(tProfileCheck, headers: anyNamed('headers')), - ).thenAnswer((_) => Future(() => Response(json.encode(response), 400))); + mockClient.post(tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) => Future(() => Response(json.encode(response), 401))); await tester.pumpWidget(getWidget()); await tester.pumpAndSettle(); // Act await tester.tap(find.byKey(const ValueKey('toggleCustomServerButton'))); await tester.pump(); - await tester.tap(find.byKey(const ValueKey('toggleApiTokenButton'))); + await tester.tap(find.byKey(const ValueKey('toggleRefreshTokenButton'))); await tester.pump(); - await tester.enterText( - find.byKey(const ValueKey('inputApiToken')), - '31e2ea0322c07b9df583a9b6d1e794f7139e78d4', - ); + await tester.enterText(find.byKey(const ValueKey('inputRefreshToken')), validJwt); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); @@ -271,25 +289,16 @@ void main() { expect(find.textContaining('Detail'), findsOne); expect(find.textContaining('Invalid token'), findsOne); verify( - mockClient.get( - tProfileCheck, - headers: argThat( - predicate( - (headers) => - headers is Map && - headers['authorization'] == 'Token 31e2ea0322c07b9df583a9b6d1e794f7139e78d4', - ), - named: 'headers', - ), - ), - ); - verifyNever( mockClient.post( - any, + tHeadlessRefresh, headers: anyNamed('headers'), body: anyNamed('body'), ), ); + // The username/password endpoint must not be hit. + verifyNever( + mockClient.post(tHeadlessLogin, headers: anyNamed('headers'), body: anyNamed('body')), + ); }); }); @@ -342,7 +351,7 @@ void main() { expect(find.textContaining('An Error Occurred'), findsNothing); verify( mockClient.post( - tRegistration, + tHeadlessSignup, headers: anyNamed('headers'), body: json.encode({'username': 'testuser', 'password': '123456789'}), ), @@ -363,7 +372,7 @@ void main() { when( mockClient.post( - tRegistration, + tHeadlessSignup, headers: anyNamed('headers'), body: anyNamed('body'), ), @@ -386,7 +395,7 @@ void main() { verify( mockClient.post( - tRegistration, + tHeadlessSignup, headers: anyNamed('headers'), body: json.encode({'username': 'testuser', 'password': '123456789'}), ), diff --git a/test/auth/auth_screen_test.mocks.dart b/test/auth/auth_screen_test.mocks.dart index 9d1250f38..595fee86d 100644 --- a/test/auth/auth_screen_test.mocks.dart +++ b/test/auth/auth_screen_test.mocks.dart @@ -10,6 +10,7 @@ import 'dart:typed_data' as _i6; import 'package:http/http.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i5; +import 'package:wger/providers/secure_token_storage.dart' as _i7; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -216,3 +217,38 @@ class MockClient extends _i1.Mock implements _i2.Client { returnValueForMissingStub: null, ); } + +/// A class which mocks [SecureTokenStorage]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockSecureTokenStorage extends _i1.Mock implements _i7.SecureTokenStorage { + MockSecureTokenStorage() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future writeRefreshToken(String? token) => + (super.noSuchMethod( + Invocation.method(#writeRefreshToken, [token]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future readRefreshToken() => + (super.noSuchMethod( + Invocation.method(#readRefreshToken, []), + returnValue: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteRefreshToken() => + (super.noSuchMethod( + Invocation.method(#deleteRefreshToken, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index d0e134caa..20716b8e0 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -251,12 +251,12 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { as String); @override - String get useApiToken => + String get useRefreshToken => (super.noSuchMethod( - Invocation.getter(#useApiToken), + Invocation.getter(#useRefreshToken), returnValue: _i3.dummyValue( this, - Invocation.getter(#useApiToken), + Invocation.getter(#useRefreshToken), ), ) as String); @@ -273,34 +273,45 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { as String); @override - String get apiToken => + String get refreshToken => (super.noSuchMethod( - Invocation.getter(#apiToken), + Invocation.getter(#refreshToken), returnValue: _i3.dummyValue( this, - Invocation.getter(#apiToken), + Invocation.getter(#refreshToken), ), ) as String); @override - String get invalidApiToken => + String get invalidRefreshToken => (super.noSuchMethod( - Invocation.getter(#invalidApiToken), + Invocation.getter(#invalidRefreshToken), returnValue: _i3.dummyValue( this, - Invocation.getter(#invalidApiToken), + Invocation.getter(#invalidRefreshToken), ), ) as String); @override - String get apiTokenValidChars => + String get refreshTokenValidChars => (super.noSuchMethod( - Invocation.getter(#apiTokenValidChars), + Invocation.getter(#refreshTokenValidChars), returnValue: _i3.dummyValue( this, - Invocation.getter(#apiTokenValidChars), + Invocation.getter(#refreshTokenValidChars), + ), + ) + as String); + + @override + String get refreshTokenHelperText => + (super.noSuchMethod( + Invocation.getter(#refreshTokenHelperText), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#refreshTokenHelperText), ), ) as String); diff --git a/test/exercises/add_exercise_notifier_test.dart b/test/exercises/add_exercise_notifier_test.dart index d9fece0f7..936bcb51f 100644 --- a/test/exercises/add_exercise_notifier_test.dart +++ b/test/exercises/add_exercise_notifier_test.dart @@ -94,7 +94,7 @@ void main() { }); }); - group('variation setters — mutual exclusion', () { + group('variation setters, mutual exclusion', () { test('setVariationGroup clears variationConnectToExercise', () { final n = container.read(addExerciseProvider.notifier); n.setVariationConnectToExercise(42); diff --git a/test/exercises/add_exercise_state_test.dart b/test/exercises/add_exercise_state_test.dart index 7e4b7d003..ea36c0443 100644 --- a/test/exercises/add_exercise_state_test.dart +++ b/test/exercises/add_exercise_state_test.dart @@ -47,7 +47,7 @@ void main() { }); }); - group('exerciseApiObject — English-only submission', () { + group('exerciseApiObject, English-only submission', () { const state = AddExerciseState( author: 'Alice', exerciseNameEn: 'Bench Press', @@ -86,7 +86,7 @@ void main() { }); }); - group('exerciseApiObject — with translation', () { + group('exerciseApiObject, with translation', () { const state = AddExerciseState( author: 'Alice', exerciseNameEn: 'Bench Press', diff --git a/test/exercises/exercise_filters_notifier_test.dart b/test/exercises/exercise_filters_notifier_test.dart index 35b7129ef..2eb6448b6 100644 --- a/test/exercises/exercise_filters_notifier_test.dart +++ b/test/exercises/exercise_filters_notifier_test.dart @@ -104,7 +104,7 @@ void main() { final container = await primedContainer(); final state = container.read(exerciseListFiltersProvider); - // 1-char search term is below the threshold — should return all. + // 1-char search term is below the threshold, should return all. container .read(exerciseListFiltersProvider.notifier) .setFilters(state.filters.copyWith(searchTerm: 'D')); diff --git a/test/fake_connectivity.dart b/test/fake_connectivity.dart index 6ac3fb34e..2160b8e22 100644 --- a/test/fake_connectivity.dart +++ b/test/fake_connectivity.dart @@ -26,14 +26,14 @@ import 'package:wger/providers/network_provider.dart'; /// /// Without this, `NetworkStatus.check()` would do a real `InternetAddress.lookup` /// against `google.com` from every test that touches a provider depending on -/// the network state — slow, non-deterministic (CI vs no CI internet), and +/// the network state, slow, non-deterministic (CI vs no CI internet), and /// hits an external host from the test runner. /// /// The [ConnectivityPlatform.instance] swap follows the officially recommended /// pattern from connectivity_plus' own tests: /// https://github.com/fluttercommunity/plus_plugins/blob/main/packages/connectivity_plus/connectivity_plus/test/connectivity_test.dart /// -/// Call once per test file (top of `main()` is fine — the static swaps stick +/// Call once per test file (top of `main()` is fine, the static swaps stick /// for the entire file). void installFakeConnectivity() { ConnectivityPlatform.instance = _FakeConnectivityPlatform(); diff --git a/test/helpers/in_memory_drift.dart b/test/helpers/in_memory_drift.dart index 63c5aa027..a94c08b1b 100644 --- a/test/helpers/in_memory_drift.dart +++ b/test/helpers/in_memory_drift.dart @@ -23,7 +23,7 @@ import 'package:wger/database/powersync/database.dart'; /// SQLite instance. The schema is created explicitly because the production /// migration is a no-op (PowerSync owns the schema in production). /// -/// Each call returns an isolated database — call this in `setUp`, and call +/// Each call returns an isolated database, call this in `setUp`, and call /// `db.close()` in `tearDown`. Future openTestDatabase() async { final db = DriftPowersyncDatabase(NativeDatabase.memory()); diff --git a/test/nutrition/ingredient_typeahead_test.dart b/test/nutrition/ingredient_typeahead_test.dart index 388152fc0..626b8dab2 100644 --- a/test/nutrition/ingredient_typeahead_test.dart +++ b/test/nutrition/ingredient_typeahead_test.dart @@ -259,7 +259,7 @@ void main() { await tester.tap(find.byIcon(Icons.tune)); await tester.pumpAndSettle(); - // Move the slider off the Off position — index 1 is the first grade, A + // Move the slider off the Off position, index 1 is the first grade, A final sliderFinder = find.byType(Slider); final Slider slider = tester.widget(sliderFinder); slider.onChanged!(1.0); @@ -272,7 +272,7 @@ void main() { await tester.enterText(find.byType(TextFormField), 'Apple'); await tester.pump(const Duration(milliseconds: 600)); - // Assert — index 1 maps to NutriScore.a + // Assert, index 1 maps to NutriScore.a verify( mockIngredientRepo.searchIngredientServer( 'Apple', diff --git a/test/nutrition/nutrition_provider_test.dart b/test/nutrition/nutrition_provider_test.dart index 6667c65c9..a30a22908 100644 --- a/test/nutrition/nutrition_provider_test.dart +++ b/test/nutrition/nutrition_provider_test.dart @@ -55,7 +55,7 @@ void main() { when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(plans)); final container = makeContainer(); // Explicit listener keeps the provider element alive while we wait for - // the Drift-stream emission to propagate — in unit tests there is no + // the Drift-stream emission to propagate, in unit tests there is no // widget pump that would do this for us. container.listen(nutritionProvider, (_, _) {}); await pumpEventQueue(); @@ -227,7 +227,7 @@ void main() { final container = makeContainer(); final result = await container.read(nutritionProvider.notifier).addPlan(toAdd); - // Notifier no longer mints — the repository (Drift's clientDefault) + // Notifier no longer mints, the repository (Drift's clientDefault) // does, on insert. The mock doesn't run that, so id stays null here. expect(identical(result, toAdd), isTrue); verify(mockRepo.addPlanLocalDrift(toAdd)).called(1); diff --git a/test/nutrition/nutrition_repository_test.dart b/test/nutrition/nutrition_repository_test.dart index 0123a74fd..0545a275c 100644 --- a/test/nutrition/nutrition_repository_test.dart +++ b/test/nutrition/nutrition_repository_test.dart @@ -163,7 +163,7 @@ void main() { const planUuid2 = 'cc000000-0000-4000-8000-000000000002'; const planUuid3 = 'cc000000-0000-4000-8000-000000000003'; - group('Plans — Drift', () { + group('Plans, Drift', () { test('watchAllDrift emits an empty list when no plans exist', () async { expect(await repo.watchAllDrift().first, isEmpty); }); @@ -374,7 +374,7 @@ void main() { }); }); - group('Meals — watchAllMealsHydrated', () { + group('Meals, watchAllMealsHydrated', () { const mealUuid1 = 'aa000000-0000-4000-8000-000000000001'; const mealUuid2 = 'aa000000-0000-4000-8000-000000000002'; const itemUuid1 = 'bb000000-0000-4000-8000-000000000001'; diff --git a/test/nutrition/nutritional_meal_form_test.dart b/test/nutrition/nutritional_meal_form_test.dart index 92d9835da..80fce15b6 100644 --- a/test/nutrition/nutritional_meal_form_test.dart +++ b/test/nutrition/nutritional_meal_form_test.dart @@ -55,7 +55,7 @@ void main() { when(mockRepo.addMealLocalDrift(any)).thenAnswer((_) async => Future.value()); when(mockRepo.editMealLocalDrift(any)).thenAnswer((_) async => Future.value()); // NutritionNotifier.build() subscribes to three Drift streams (plans, - // meals, diary entries) — emit the seed plan and empty meals/diary so the + // meals, diary entries), emit the seed plan and empty meals/diary so the // combined stream produces a value. when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1])); when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals)); diff --git a/test/nutrition/nutritional_meal_item_form_test.dart b/test/nutrition/nutritional_meal_item_form_test.dart index f96de74df..ce497aa9f 100644 --- a/test/nutrition/nutritional_meal_item_form_test.dart +++ b/test/nutrition/nutritional_meal_item_form_test.dart @@ -137,7 +137,7 @@ void main() { // separate stub is needed. when(mockIngredientRepo.getById(any)).thenAnswer((_) async => ingredient); // NutritionNotifier.build() subscribes to three Drift streams (plans, - // meals, diary entries) — emit the seed plan and meals so the combined + // meals, diary entries), emit the seed plan and meals so the combined // stream produces a value. when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([plan1])); when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value(plan1.meals)); diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index 4f0d54ad6..3ca28487c 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -78,7 +78,7 @@ void main() { mockNutritionRepo.watchAllLogsHydrated(), ).thenAnswer((_) => Stream.value(getTestNutritionLogs())); - // Ingredient lookups now go through PowerSync — stub the local repo. + // Ingredient lookups now go through PowerSync, stub the local repo. when(mockIngredientRepo.getById(any)).thenAnswer((_) async => fetchedIngredient); when(mockIngredientRepo.watchById(any)).thenAnswer((_) => Stream.value(fetchedIngredient)); }); diff --git a/test/nutrition/nutritional_plans_screen_test.dart b/test/nutrition/nutritional_plans_screen_test.dart index 22410daeb..15a1f2230 100644 --- a/test/nutrition/nutritional_plans_screen_test.dart +++ b/test/nutrition/nutritional_plans_screen_test.dart @@ -130,7 +130,7 @@ void main() { // Confirmation dialog expect(find.byType(AlertDialog), findsOneWidget); - // Confirm tap — actual delete now goes through Drift + PowerSync (not + // Confirm tap, actual delete now goes through Drift + PowerSync (not // REST), so we don't assert on the REST mock here. await tester.tap(find.text('Delete')); await tester.pumpAndSettle(); diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index 9738e4ce4..d7ea83818 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -124,7 +124,7 @@ void main() { test('does not touch DateTimeField columns even on registered tables', () { // `manager_workoutlog.date` is a DateTimeField on Django (not a // DateField), and `manager_workoutlog` isn't in the date-only - // registry — the timestamp must round-trip unchanged. + // registry, the timestamp must round-trip unchanged. final out = connector.genericTransform( 'manager_workoutlog', {'date': '2024-11-01T17:30:00.000Z'}, diff --git a/test/providers/helpers_test.dart b/test/providers/helpers_test.dart index 7535311f5..df8dcfe93 100644 --- a/test/providers/helpers_test.dart +++ b/test/providers/helpers_test.dart @@ -103,7 +103,7 @@ void main() { }); test('does not prepend the server URL for absolute URLs on different hosts', () { - // Useful when the REST API has already absolutised the URL — we must + // Useful when the REST API has already absolutised the URL, we must // not double-prefix with the local server. final result = mediaUri('https://wger.de', 'https://other.example.com/x.jpg'); expect(result?.host, 'other.example.com'); diff --git a/test/providers/media_url_prefix_notifier_test.dart b/test/providers/media_url_prefix_notifier_test.dart index 35d73e8c9..bf06b1261 100644 --- a/test/providers/media_url_prefix_notifier_test.dart +++ b/test/providers/media_url_prefix_notifier_test.dart @@ -148,7 +148,7 @@ void main() { when(mockPrefs.setString(any, any)).thenAnswer((_) async {}); when(mockPrefs.remove(any)).thenAnswer((_) async {}); when(mockBase.serverUrl).thenReturn('https://example'); - // Default fetch — empty response so the auto-probe in build is + // Default fetch, empty response so the auto-probe in build is // a harmless no-op for tests that don't care about it. stubFetch(responseBody: {'results': []}); }); @@ -186,7 +186,7 @@ void main() { final container = makeContainer(); // build() triggers an auto-probe in the background. We also - // drive the notifier explicitly for ordering — both calls are + // drive the notifier explicitly for ordering, both calls are // idempotent. Verify uses no .called() so we accept either one // or two invocations. await container.read(mediaUrlPrefixProvider.future); diff --git a/test/routine/gym_log_notifier_test.dart b/test/routine/gym_log_notifier_test.dart index e811573dd..475ba678c 100644 --- a/test/routine/gym_log_notifier_test.dart +++ b/test/routine/gym_log_notifier_test.dart @@ -68,7 +68,7 @@ void main() { expect(state.exerciseId, source.exerciseId); expect(state.weight, source.weight); expect(state.date, fixed); - // setLog must clear the id — the source log is a template, the new + // setLog must clear the id, the source log is a template, the new // state is a separate entry that will get its own UUID from Drift on // insert. expect(state.id, isNull); diff --git a/test/routine/gym_mode/gym_mode_test.dart b/test/routine/gym_mode/gym_mode_test.dart index b8e62f66f..6cca4793f 100644 --- a/test/routine/gym_mode/gym_mode_test.dart +++ b/test/routine/gym_mode/gym_mode_test.dart @@ -74,7 +74,7 @@ void main() { mockExerciseRepo.watchAllDrift(), ).thenAnswer((_) => Stream.value(ExerciseState(testExercises))); - // Drift the test routine in via the routines repository — the real + // Drift the test routine in via the routines repository, the real // [RoutinesRiverpod] picks it up and exposes it through state. when( mockRoutinesRepo.watchAllDrift(), @@ -95,7 +95,7 @@ void main() { exerciseRepositoryProvider.overrideWithValue(mockExerciseRepo), workoutSessionRepositoryProvider.overrideWithValue(mockSessionRepo), // The repetition + weight unit catalogues are tiny direct-Drift - // stream providers — overriding them inline is the established + // stream providers, overriding them inline is the established // pattern (see also [exerciseCategoriesProvider] etc.). routineRepetitionUnitProvider.overrideWith( (ref) => Stream>.value(testRepetitionUnits), @@ -174,8 +174,8 @@ void main() { expect(find.byIcon(Icons.chevron_left), findsOneWidget); expect(find.byIcon(Icons.chevron_right), findsOneWidget); - // The form shows reps and weight — each with its own unit - // picker (PopupMenuButton) — plus the RiR slider, all at + // The form shows reps and weight, each with its own unit + // picker (PopupMenuButton), plus the RiR slider, all at // once. Scope the popup-menu lookup to the LogPage so other // popup menus elsewhere in the app shell don't interfere. expect(find.byType(TextFormField), findsNWidgets(2)); @@ -187,7 +187,7 @@ void main() { findsNWidgets(2), ); expect(find.byType(RiRInputWidget), findsOneWidget); - // Advance to the next page via the chevron — the RiR slider + // Advance to the next page via the chevron, the RiR slider // would otherwise eat a horizontal-drag gesture started over // its track. await tester.tap(find.byIcon(Icons.chevron_right)); diff --git a/test/routine/helpers/routine_form_test_overrides.dart b/test/routine/helpers/routine_form_test_overrides.dart index 9f2a740a8..1d5c518da 100644 --- a/test/routine/helpers/routine_form_test_overrides.dart +++ b/test/routine/helpers/routine_form_test_overrides.dart @@ -41,7 +41,7 @@ export 'routine_form_test_overrides.mocks.dart' /// without this stub. /// /// When [exercise] / [session] are passed in by the caller they are used -/// as-is — the caller owns the stubbing. Only the locally-created fallback +/// as-is, the caller owns the stubbing. Only the locally-created fallback /// mocks get a default empty-stream stub here. List exerciseAndSessionRepoOverrides({ MockExerciseRepository? exercise, @@ -73,7 +73,7 @@ MockWorkoutSessionRepository _emptySessionRepoMock() { /// Use this in widget tests that don't override the reference-data streams /// themselves; otherwise mix in [exerciseAndSessionRepoOverrides] alone. /// -/// [repetitionUnits] / [weightUnits] default to empty lists — sufficient for +/// [repetitionUnits] / [weightUnits] default to empty lists, sufficient for /// most form widget tests where the units only need to satisfy the /// `awaitFirstValue` step. Pass real fixtures when the test exercises /// hydration logic that looks units up by id. diff --git a/test/routine/models/log_test.dart b/test/routine/models/log_test.dart index 83229b320..2c5e7ca78 100644 --- a/test/routine/models/log_test.dart +++ b/test/routine/models/log_test.dart @@ -145,7 +145,7 @@ void main() { // // When the user taps "+" in gym mode to add an extra exercise, // addExerciseAfterPage() creates a SetConfigData with only exerciseId and - // slotEntryId — no unit objects. The default constructor sets + // slotEntryId, no unit objects. The default constructor sets // weightUnitId=WEIGHT_UNIT_KG and repetitionsUnitId=REP_UNIT_REPETITIONS_ID, // but Log.fromSetConfigData was using the object setters which overwrite // those IDs with null when the objects are null, causing the server to @@ -154,7 +154,7 @@ void main() { exerciseId: 1, slotEntryId: 1, exercise: exercise, - // no weightUnit or repetitionsUnit objects — mirrors addExerciseAfterPage() + // no weightUnit or repetitionsUnit objects, mirrors addExerciseAfterPage() ); final log = Log.fromSetConfigData(setConfig); diff --git a/test/routine/routines_provider_repository_test.dart b/test/routine/routines_provider_repository_test.dart index b14196303..45de48d4d 100644 --- a/test/routine/routines_provider_repository_test.dart +++ b/test/routine/routines_provider_repository_test.dart @@ -33,7 +33,7 @@ import 'routines_provider_repository_test.mocks.dart'; void main() { final mockBaseProvider = MockWgerBaseProvider(); // The repository now takes a Drift database in its constructor, but - // none of the REST methods exercised in this file touch it — a plain + // none of the REST methods exercised in this file touch it, a plain // mock instance is enough. final mockDb = MockDriftPowersyncDatabase(); diff --git a/test/routine/routines_provider_test.dart b/test/routine/routines_provider_test.dart index c21c66b5f..afccbc4f7 100644 --- a/test/routine/routines_provider_test.dart +++ b/test/routine/routines_provider_test.dart @@ -51,7 +51,7 @@ void main() { mockRepo = MockRoutinesRepository(); when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value(const [])); // Mock repos for the two reference-data notifiers `fetchAndSetRoutineFull` - // awaits — kept locally so individual tests can re-stub them with + // awaits, kept locally so individual tests can re-stub them with // specific session/exercise data. mockSessionRepo = MockWorkoutSessionRepository(); when( @@ -178,7 +178,7 @@ void main() { verify(mockRepo.editDayServer(day1)).called(1); verify(mockRepo.editDayServer(day2)).called(1); // dayData/dayDataGym are server-computed, so we must refresh once after - // the batch — not once per edit. + // the batch, not once per edit. verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1); }); diff --git a/test/routine/routines_repository_test.dart b/test/routine/routines_repository_test.dart index db0ef9dd0..6af52acdb 100644 --- a/test/routine/routines_repository_test.dart +++ b/test/routine/routines_repository_test.dart @@ -73,7 +73,7 @@ void main() { // --------------------------------------------------------------------------- - group('Routines — Drift', () { + group('Routines, Drift', () { test('watchAllDrift emits an empty list when no routines exist', () async { expect(await repo.watchAllDrift().first, isEmpty); }); @@ -155,7 +155,7 @@ void main() { // else lives here. // --------------------------------------------------------------------------- - group('Days — REST', () { + group('Days, REST', () { test('addDayServer POSTs to /day/ and returns the created Day', () async { final dayUri = Uri.https('localhost', 'api/v2/day/'); when(mockBase.makeUrl('day')).thenReturn(dayUri); @@ -200,7 +200,7 @@ void main() { }); }); - group('Slots — REST', () { + group('Slots, REST', () { test('addSlotServer POSTs to /slot/ and returns the created Slot', () async { final uri = Uri.https('localhost', 'api/v2/slot/'); when(mockBase.makeUrl('slot')).thenReturn(uri); @@ -232,7 +232,7 @@ void main() { }); }); - group('Slot entries — REST', () { + group('Slot entries, REST', () { SlotEntry makeEntry({int? id, int slotId = 1}) { // `config` is `late Object?` and required for toJson to work. return SlotEntry( @@ -292,7 +292,7 @@ void main() { }); }); - group('Configs — REST', () { + group('Configs, REST', () { Map configResponse(int id, num value) => { 'id': id, 'iteration': 1, diff --git a/test/routine/routines_screen_test.dart b/test/routine/routines_screen_test.dart index 2cfa7f156..05364f089 100644 --- a/test/routine/routines_screen_test.dart +++ b/test/routine/routines_screen_test.dart @@ -108,7 +108,7 @@ void main() { // Confirmation dialog expect(find.byType(AlertDialog), findsOneWidget); - // Confirm tap — note: the actual delete now goes through Drift + + // Confirm tap, note: the actual delete now goes through Drift + // PowerSync (not REST), so we don't verify a repository call here. // The UI flow up to dispatch is what's covered. await tester.tap(find.text('Delete')); diff --git a/test/routine/workout_logs_repository_test.dart b/test/routine/workout_logs_repository_test.dart index 2e3b42124..972108a6f 100644 --- a/test/routine/workout_logs_repository_test.dart +++ b/test/routine/workout_logs_repository_test.dart @@ -58,7 +58,7 @@ void main() { Future> readLogs() => db.select(db.workoutLogTable).get(); Future> readSessions() => db.select(db.workoutSessionTable).get(); - group('addLocalDrift — log already has a sessionId', () { + group('addLocalDrift, log already has a sessionId', () { test('inserts the log without touching the session table', () async { final log = makeLog(sessionId: 'existing-session'); @@ -71,7 +71,7 @@ void main() { }); }); - group('addLocalDrift — log without sessionId', () { + group('addLocalDrift, log without sessionId', () { test('reuses an existing session for the same routine and day', () async { final existingSession = WorkoutSession( id: 'existing-session-1', diff --git a/test/screens/recovery_screens_test.dart b/test/screens/recovery_screens_test.dart index c6d811f4d..b09e9f672 100644 --- a/test/screens/recovery_screens_test.dart +++ b/test/screens/recovery_screens_test.dart @@ -70,7 +70,7 @@ void main() { supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('en'), // logout buttons in the recovery screens navigate to '/' after - // calling the notifier — register both the entry route and a + // calling the notifier, register both the entry route and a // stub for '/' so the navigation succeeds in tests. We can't // use `home` here since that conflicts with a routes['/'] entry. initialRoute: '/test', diff --git a/test/widgets/core/error_test.dart b/test/widgets/core/error_test.dart index 56a834569..b667719a0 100644 --- a/test/widgets/core/error_test.dart +++ b/test/widgets/core/error_test.dart @@ -128,7 +128,7 @@ void main() { await tester.pumpAndSettle(); // The body is wrapped in a ConstrainedBox(maxHeight: 280). Pull it out - // of the tree and assert the cap is in place — this is what stops the + // of the tree and assert the cap is in place, this is what stops the // dashboard cards from growing unbounded. final constrained = tester .widgetList(find.byType(ConstrainedBox))