Compare commits

...

2 Commits

Author SHA1 Message Date
a2ce5049f0 Qualify a run on EITHER duration or distance, not both
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
MIN_RUN_DURATION_MINUTES and MIN_RUN_DISTANCE_KM were an AND (30+ min AND
5.0+ km), which rejected a fast 5 km run that took under 30 minutes. They
are now an OR at 40 min / 3.5 km: a run qualifies at either threshold
alone. Distance keeps its 5% GPS tolerance; duration, from the device
clock, does not.

Fixed one stale test whose fixture (1 min / 6 km) predated the OR change:
6 km alone now qualifies under the new rule, so the fixture needed to fail
BOTH branches to still exercise the "no file verified, return first
result" path it was written for.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-14 11:04:18 +02:00
5d4d491fb7 workout_app: add Google sign-in support for the Firebase sync account
Same pattern as todo and diet_guard_app: openFirebaseWithGoogle()
(google_platform.dart abstracts the plugin's platform-channel
dependence), isFirebaseConfigured() reading the stored session rather
than the account marker alone, and the settings screen offering
"Sign in with Google" ahead of the password form.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
2026-08-14 10:56:16 +02:00
21 changed files with 920 additions and 38 deletions

View File

@ -419,6 +419,20 @@
stores the true, un-inflated distance.
</p>
<div class="note" style="border-left:4px solid #b58900;padding:0.75rem 1rem;margin:1.5rem 0;background:#fdf6e3">
<strong>Superseded 2026-08-14.</strong> The numbers on this page describe the
rule as it stood on 2026-07-18 and are kept for that history. The thresholds
and their <em>shape</em> have both since changed: duration and distance were
an <strong>AND</strong> here (30+ min <em>and</em> 5.0+ km); they are now an
<strong>OR</strong> — a run qualifies at
<code>MIN_RUN_DISTANCE_KM = 3.5</code> (inclusive, still with the 5% GPS
tolerance described above) <em>or</em> at
<code>MIN_RUN_DURATION_MINUTES = 40</code> (strict, no tolerance). The
30-minute floor every run had to clear is gone, so a fast 5&nbsp;km now
passes too. The interactive demo and quiz below still use the old 5.0&nbsp;km
AND-rule.
</div>
<h3>3.5 The CLI bug this surfaced (unrelated file, same root cause)</h3>
<p>

View File

@ -58,8 +58,12 @@ WORKOUT_HTTP_PORT = 8765
MIN_WORKOUT_DURATION_MINUTES = 60
RUNNERUP_PACKAGES = ("org.runnerup", "org.runnerup.free")
RUNNERUP_DB_SDCARD_TMP = "/sdcard/.runnerup_tmp_verification.db"
MIN_RUN_DURATION_MINUTES = 30
MIN_RUN_DISTANCE_KM = 5.0
# A run qualifies on EITHER criterion — they are an OR, not an AND. A short
# but long-lasting run counts, and so does a fast 5 km that takes under 40 min.
# Do not reinstate an AND here: it would reject exactly the slow-run case this
# pair exists to allow.
MIN_RUN_DURATION_MINUTES = 40 # strict: "over 40 minutes"
MIN_RUN_DISTANCE_KM = 3.5 # inclusive: "as low as 3.5 km"
# GPS distance tracking undershoots on tight turns/tree cover/urban canyons;
# a run within 5% of the minimum is accepted rather than rejected on
# measurement noise. Duration comes from the device clock, not GPS, so it

View File

@ -245,17 +245,22 @@ class RunnerUpVerificationMixin(RunnerUpDbMixin):
)
duration_min = data["duration_seconds"] / 60
if duration_min < MIN_RUN_DURATION_MINUTES:
distance_km = data["distance_m"] / 1000
# Either criterion qualifies the run on its own (see _constants.py).
# Distance gets the GPS tolerance; duration, from the device clock,
# does not.
distance_ok = (
distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) >= MIN_RUN_DISTANCE_KM
)
duration_ok = duration_min > MIN_RUN_DURATION_MINUTES
if not distance_ok and not duration_ok:
msg = (
f"Run was {duration_min:.0f} min — need {MIN_RUN_DURATION_MINUTES}+ min"
f"Run was {distance_km:.1f} km / {duration_min:.0f} min — need "
f"{MIN_RUN_DISTANCE_KM:g}+ km or {MIN_RUN_DURATION_MINUTES}+ min"
)
return "too_short", msg
distance_km = data["distance_m"] / 1000
if distance_km * (1 + RUNNERUP_DISTANCE_TOLERANCE) < MIN_RUN_DISTANCE_KM:
msg = f"Run was {distance_km:.1f} km — need {MIN_RUN_DISTANCE_KM:.0f}+ km"
return "too_short", msg
if distance_km < MIN_RUN_DISTANCE_KM:
if distance_ok and distance_km < MIN_RUN_DISTANCE_KM:
_logger.info(
"RunnerUp distance %.2f km is under the %.1f km minimum but "
"within %.0f%% GPS tolerance — accepted.",

View File

@ -113,19 +113,23 @@ class TestValidateRunnerupData:
assert status == "wrong_sport"
assert "unknown(99)" in msg
def test_too_short_duration_returns_too_short(
def test_short_duration_alone_still_verified_on_distance(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Duration below MIN_RUN_DURATION_MINUTES → too_short with 'min' in message."""
"""Short duration alone is not enough to reject — distance still qualifies.
The criteria are an OR, so 6 km in 1 min is verified on distance. If
the OR ever regressed to an AND this would return too_short.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 60, "distance_m": 6000}
)
assert status == "too_short"
assert "min" in msg
assert status == "verified"
assert "6.0 km" in msg
def test_too_short_distance_returns_too_short(
self,
@ -133,13 +137,18 @@ class TestValidateRunnerupData:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Distance below MIN_RUN_DISTANCE_KM → too_short with 'km' in message."""
"""Both criteria missed → too_short naming both.
0.1 km is far under the distance line and 30 min is under the duration
line, so neither branch of the OR qualifies.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2400, "distance_m": 100}
{"sport": 0, "duration_seconds": 1800, "distance_m": 100}
)
assert status == "too_short"
assert "km" in msg
assert "3.5+ km" in msg
assert "40+ min" in msg
def test_valid_run_returns_verified(
self,

View File

@ -89,13 +89,17 @@ class TestValidateRunnerupDataDistanceTolerance:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""4.9 km * 1.05 = 5.145 >= 5.0 km minimum → verified."""
"""3.45 km * 1.05 = 3.62 >= 3.5 km minimum → verified.
Duration is held under 40 min so the distance branch is what is
actually under test, not the duration branch of the OR.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1947, "distance_m": 4929.05}
{"sport": 0, "duration_seconds": 1500, "distance_m": 3450.0}
)
assert status == "verified"
assert "4.9 km" in msg
assert "3.5 km" in msg
def test_distance_below_tolerance_is_too_short(
self,
@ -103,13 +107,16 @@ class TestValidateRunnerupDataDistanceTolerance:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""4.0 km * 1.05 = 4.2 km, still short of the 5.0 km minimum → too_short."""
"""3.0 km * 1.05 = 3.15 km, still short of the 3.5 km minimum → too_short.
Duration is under 40 min so the duration branch cannot rescue it.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1947, "distance_m": 4000}
{"sport": 0, "duration_seconds": 1500, "distance_m": 3000}
)
assert status == "too_short"
assert "km" in msg
assert "3.5+ km" in msg
def test_distance_at_full_minimum_is_verified(
self,
@ -126,6 +133,104 @@ class TestValidateRunnerupDataDistanceTolerance:
assert status == "verified"
class TestValidateRunnerupDataOrCriteria:
"""Distance and duration are an OR: either one alone qualifies a run."""
def test_long_but_short_distance_is_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""2 km in 45 min → verified on the duration branch alone."""
locker = create_locker(mock_tk, tmp_path)
status, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2700, "distance_m": 2000}
)
assert status == "verified"
def test_far_but_quick_is_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""3.6 km in 20 min → verified on the distance branch alone.
The old rule imposed a 30-minute floor on every run; it is gone, so a
fast run is no longer rejected for being quick.
"""
locker = create_locker(mock_tk, tmp_path)
status, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1200, "distance_m": 3600}
)
assert status == "verified"
def test_neither_criterion_met_is_too_short(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""3.0 km in 25 min misses both branches; message names both."""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1500, "distance_m": 3000}
)
assert status == "too_short"
# Pinned literally: a ':.0f' format spec would render 3.5 as "4".
assert "need 3.5+ km or 40+ min" in msg
def test_distance_boundary_is_inclusive(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Exactly 3.5 km qualifies ("as low as 3.5 km")."""
locker = create_locker(mock_tk, tmp_path)
status, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 600, "distance_m": 3500}
)
assert status == "verified"
def test_duration_boundary_is_strict(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Exactly 40 min does not qualify, but 40.1 min does ("over 40")."""
locker = create_locker(mock_tk, tmp_path)
at_boundary, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2400, "distance_m": 1000}
)
assert at_boundary == "too_short"
just_over, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2406, "distance_m": 1000}
)
assert just_over == "verified"
def test_real_2026_08_14_run_is_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Regression: the real run this rule change was made for.
Pulled from RunnerUp_2026-08-14-00-58-45_Running.tcx — 4 laps summing
to 3817 m / 2502 s. It qualifies on both branches; under the previous
AND rule it was rejected with "Run was 3.8 km — need 5+ km".
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2502, "distance_m": 3817.0}
)
assert status == "verified"
assert "3.8 km" in msg
# ---------------------------------------------------------------------------
# _validate_runnerup_data
# ---------------------------------------------------------------------------
@ -178,7 +283,14 @@ class TestVerifyRunnerupViaFiles:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Files found but none verified → returns first non-None validation result."""
"""Files found but none verified → returns first non-None validation result.
Both duration and distance are held under their minimums so the OR
in _validate_runnerup_data cannot rescue this fixture on either
branch — otherwise a fixture qualifying on one branch alone would
turn this into a test of that branch, not of the "no file verified"
return-first-result behavior this test is actually about.
"""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
@ -189,7 +301,7 @@ class TestVerifyRunnerupViaFiles:
locker,
"_pull_and_parse_tcx",
MagicMock(
return_value={"sport": 0, "duration_seconds": 60, "distance_m": 6000}
return_value={"sport": 0, "duration_seconds": 60, "distance_m": 1000}
),
)
result = locker._verify_runnerup_via_files()

View File

@ -217,7 +217,13 @@ class TestScanAndFillWeekRunnerup:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""_validate_runnerup_data returns not-verified → date not filled."""
"""_validate_runnerup_data returns not-verified → date not filled.
Both duration and distance are held under their minimums -- the
criteria are an OR, so a fixture qualifying on either alone would
verify instead of exercising the not-verified path this test is
about.
"""
locker = create_locker(mock_tk, tmp_path)
log_file = tmp_path / "log.json"
log_file.write_text("{}")
@ -231,7 +237,7 @@ class TestScanAndFillWeekRunnerup:
locker,
"_pull_and_parse_tcx",
MagicMock(
return_value={"sport": 0, "duration_seconds": 60, "distance_m": 6000}
return_value={"sport": 0, "duration_seconds": 60, "distance_m": 1000}
),
)
assert locker._scan_and_fill_week_runnerup(log_file) == 0

View File

@ -321,7 +321,10 @@ class TestBranchCoverageGaps:
of 'if best is None:' (161->154), exercising the loop-continue with best set."""
locker = create_locker(mock_tk, tmp_path)
# Both exports return non-verified data (too_short).
# Both exports return non-verified data (too_short). Duration and
# distance are an OR, so both must fail their minimum -- a fixture
# qualifying on either alone would verify instead of exercising this
# branch.
# Iteration 1: best is None → sets best → loop continues to export 2.
# Iteration 2: best is NOT None → False branch of 'if best is None:' (161->154).
object.__setattr__(
@ -329,7 +332,7 @@ class TestBranchCoverageGaps:
"_find_runnerup_exports_for_date",
MagicMock(return_value=["/sdcard/a.tcx", "/sdcard/b.tcx"]),
)
short_run = {"sport": 0, "duration_seconds": 60, "distance_m": 6000}
short_run = {"sport": 0, "duration_seconds": 60, "distance_m": 1000}
object.__setattr__(
locker,
"_pull_and_parse_tcx",

View File

@ -31,9 +31,27 @@ fi
# ── Guard: every lib/**/*.dart must appear in the coverage report ──────────────
# Flutter only reports files that are transitively imported by a test.
# Unreferenced files silently score 100% by absence — catch that here.
#
# Exception: a file whose only content is a conditional `export` (a
# platform-gate barrel like google_platform.dart, re-exporting google_platform_io.dart
# or google_platform_web.dart per dart.library.js_interop) has zero executable
# statements. Dart's coverage instrumentation never emits an SF: entry for such
# a file regardless of whether it was imported -- there is no "silently 100% by
# absence" for it to hide, since there is nothing to cover. Importing it (even
# transitively) is what makes its *resolved* sibling appear in lcov instead.
barrel_pattern="^(library;)?[[:space:]]*export[[:space:]]+'[^']+'[[:space:]]+if[[:space:]]*\([^)]+\)[[:space:]]+'[^']+';[[:space:]]*\$"
missing=0
while IFS= read -r dart_file; do
rel="${dart_file#"$APP_DIR"/}"
# Strip //-comments, ///-doc-comments and blank lines, then collapse
# whitespace, so a wrapped `export 'x' if (...) 'y';` statement (the
# platform-gate barrel shape) becomes matchable on one logical line
# regardless of how it's line-wrapped in source.
code_only=$(grep -vE '^[[:space:]]*(///|//|$)' "$dart_file" | tr '\n' ' ' | tr -s ' ')
if [[ $code_only =~ $barrel_pattern ]]; then
continue
fi
if ! grep -qF "SF:$rel" "$LCOV_INFO" && \
! grep -qF "SF:lib/${rel#lib/}" "$LCOV_INFO"; then
echo "MISSING FROM COVERAGE: $dart_file" >&2

View File

@ -13,6 +13,7 @@ import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/github_device_auth.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_settings.dart';
@ -28,9 +29,12 @@ class SettingsScreen extends StatefulWidget {
super.key,
this.httpClient,
this.firebaseFactory,
this.googleFirebaseFactory,
this.googleAvailable,
this.accountLoader,
this.accountSaver,
this.accountClearer,
this.sessionProbe,
this.storageChecker,
this.storageRequester,
this.progressionPuller,
@ -43,6 +47,15 @@ class SettingsScreen extends StatefulWidget {
/// Builds the Firebase client. Injected so tests need no platform channel.
final Future<FirebaseRestClient?> Function()? firebaseFactory;
/// Builds the Firebase backend via Google sign-in. Separate from
/// [firebaseFactory] because it reaches the Google plugin's platform
/// channel, which `flutter test` has no binding for.
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
/// Whether to offer the Google button. Defaults to what the platform
/// supports; injected by tests, whose host reports unsupported.
final bool? googleAvailable;
/// Keystore accessors for the Firebase account. Injected as a group so the
/// connect/disconnect flows are testable without a platform channel --
/// `flutter test` has no binding for one.
@ -54,6 +67,15 @@ class SettingsScreen extends StatefulWidget {
/// Forgets the account and any cached session. See [accountLoader].
final Future<void> Function()? accountClearer;
/// Whether a Firebase session is stored. See [accountLoader].
///
/// Separate from [accountLoader] because the two answer different
/// questions: the account marker is bookkeeping, the session is the
/// credential. A device can hold the second without the first, and
/// reporting only the first is what made a syncing phone read as
/// "not connected".
final Future<bool> Function()? sessionProbe;
/// Reads whether storage permission is held. Injected for the same reason as
/// [accountLoader]: `permission_handler` is a platform channel, and calling
/// it unguarded in `initState` made every settings-screen test throw.
@ -136,9 +158,74 @@ class _SettingsScreenState extends State<SettingsScreen> {
/// state instead of an empty form that looks unconfigured.
Future<void> _loadFirebaseAccount() async {
final account = await (widget.accountLoader ?? loadAccount)();
// The stored session, not the account marker, decides "connected": a
// Google sign-in leaves a refresh token that authenticates every request
// even when no marker was written beside it.
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
if (!mounted) return;
if (account != null) _emailController.text = account.email;
setState(() => _firebaseConnected = account != null);
setState(() => _firebaseConnected = connected);
}
/// Signs in by picking a Google account -- the one-tap path.
///
/// A dismissed picker is not an error; a wrong-account sign-in reports why,
/// because that is the failure that otherwise looks like a working sync
/// which silently never syncs.
Future<void> _connectGoogle() async {
setState(() => _firebaseBusy = true);
try {
final client =
await (widget.googleFirebaseFactory ?? openFirebaseWithGoogle)();
if (!mounted) return;
if (client == null) {
setState(() => _firebaseBusy = false);
_setSyncStatus(
'Google sign-in was cancelled.',
_SyncStatusKind.pending,
);
return;
}
// openFirebaseWithGoogle stored the account under the email Firebase
// reported; reflect it rather than reading the (empty) form field.
final account = await (widget.accountLoader ?? storedAccount)();
// Report the persisted state, not the fact that the call returned a
// client: a non-null client only means sign-in succeeded in that
// moment, which is how four apps claimed "Connected" and then synced
// over GitHub after the next restart.
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
if (!mounted) return;
if (account != null) _emailController.text = account.email;
setState(() {
_firebaseBusy = false;
_firebaseConnected = connected;
});
_setSyncStatus(
connected
? 'Connected to Firebase.'
: 'Signed in, but this device did not save the session - it will '
'sync over GitHub after a restart. Try connecting again.',
connected ? _SyncStatusKind.success : _SyncStatusKind.error,
);
} on FirebaseAuthError catch (error) {
if (!mounted) return;
setState(() {
_firebaseBusy = false;
_firebaseConnected = false;
});
_setSyncStatus(error.message, _SyncStatusKind.error);
} on Object catch (error) {
// Broader than Exception on purpose: a missing platform binding raises
// an Error, and anything escaping here leaves the button disabled and
// the screen stuck forever -- which is what happened on the phone
// before storedAccount() replaced loadAccount().
if (!mounted) return;
setState(() {
_firebaseBusy = false;
_firebaseConnected = false;
});
_setSyncStatus('Google sign-in failed: $error', _SyncStatusKind.error);
}
}
/// Stores the typed account and signs in immediately, so a typo surfaces
@ -183,8 +270,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
// workout would push those defaults over the top. Connecting late is the
// normal path after a reinstall (the uninstall wipes the keystore), so
// this is the common case, not an edge one.
final restored = await (widget.progressionPuller ??
ProgressionSyncService().pullProgression)();
final restored =
await (widget.progressionPuller ??
ProgressionSyncService().pullProgression)();
if (!mounted) return;
setState(() {
@ -583,6 +671,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
icon: const Icon(Icons.cloud_done),
label: const Text('Connect Firebase'),
),
// One tap, no typing -- the path that matters after a
// reinstall. Hidden where the platform has no programmatic
// Google flow (see google_platform.dart), because a button
// that always failed would be worse than none.
if (widget.googleAvailable ?? googleSignInSupported) ...[
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: _firebaseBusy ? null : _connectGoogle,
icon: const Icon(Icons.account_circle),
label: const Text('Sign in with Google'),
),
],
],
const SizedBox(height: 8),
// GitHub is the cutover mirror, not a choice competing with

View File

@ -16,6 +16,8 @@ import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/services/google_sign_in_backend.dart';
/// The shared `kuhy-syncs` project.
///
@ -78,6 +80,17 @@ Future<FirebaseAccount?> loadAccount() async {
}
}
/// Reads the account from the keystore only, with no wrapper fallback.
///
/// [loadAccount] falls back to the desktop wrapper's `/sync-account` route
/// when the keystore is empty, which on Android resolves to `file:///` and
/// throws `No host specified in URI`. Callers reading back an account they
/// just wrote -- where a fallback would be wrong anyway -- use this instead.
/// Verified on the phone: without it, sign-in succeeded and then the settings
/// screen hung on "Signing in..." forever.
Future<FirebaseAccount?> storedAccount() async =>
FirebaseAccount.tryParse(await _secure.read(key: kFirebaseAccountKey));
/// Stores the per-device account. Keystore only — never prefs, never source.
Future<void> saveAccount(FirebaseAccount account) =>
_secure.write(key: kFirebaseAccountKey, value: account.toJsonString());
@ -94,12 +107,131 @@ Future<void> clearAccount() async {
/// token, so the usual path costs no authentication round trip.
Future<FirebaseRestClient?> openFirebase() async {
final account = await loadAccount();
if (account == null) return null;
if (account == null) {
// A stored refresh token IS a signed-in device, even with no account
// marker beside it. Treating the marker as the source of truth is what
// made a phone with a live session sync over GitHub and 401 forever --
// the credential was in the keystore the whole time, unused.
return _clientFromStoredSession();
}
return firebaseClientFor(
config: kProject.configFor(account.email),
store: credentialStore(),
password: account.password,
// A Google-provisioned account stores an empty password.
// Passing '' would make firebaseClientFor treat it as a usable
// credential and sign in with it, which fails; null correctly
// means "no password on this device".
password: account.password.isEmpty ? null : account.password,
// Deliberately NOT offering Google here. This path runs from background
// timers and, in some apps, before runApp -- offering it would let a
// non-interactive tick raise the OS account picker with no user action
// behind it. Interactive sign-in uses openFirebaseWithGoogle instead.
expectedUid: kSyncUid,
);
}
/// Signs in with Google alone, for a device that has no account stored yet.
///
/// This is the one-tap path: [openFirebase] needs an account in the keystore
/// to know which email to use, but a fresh install has none. The Google token
/// carries the identity, so nothing needs to be typed.
///
/// The account is stored under the email **Firebase reports**, never one read
/// from the UI: a fresh install has no email anywhere on the device, so taking
/// it from a text field would persist an empty account and send the next
/// launch down the password path with ''.
///
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
/// when Google succeeds but resolves to a uid the security rules do not pin,
/// which would otherwise authenticate fine and then be denied every read and
/// write with no other symptom.
Future<FirebaseRestClient?> openFirebaseWithGoogle({
Future<String?> Function()? tokenFetcher,
Future<void> Function(FirebaseAccount)? accountSaver,
http.Client? httpClient,
}) async {
final token = await (tokenFetcher ?? googleIdToken)();
if (token == null) return null;
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
httpClient: httpClient,
);
final email = await auth.signInWithGoogle(
idToken: token,
expectedUid: kSyncUid,
);
// Saved unconditionally, and deliberately not gated on `email`:
// `signInWithIdp` omits that field whenever the Google account hides it, and
// gating the write on it returned a working client while persisting nothing,
// so the next launch looked unconfigured and fell back to GitHub-only.
// The session itself is already durable here -- signInWithGoogle stored the
// refresh token -- and that token, not the address, is the credential.
await (accountSaver ?? saveAccount)(
FirebaseAccount(email: email ?? '', password: ''),
);
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
}
/// Whether this device can actually authenticate against Firebase.
///
/// True when either half of the state is present: the account marker
/// [loadAccount] reads, or a stored refresh token. The token is the half that
/// matters -- it is what signs requests -- so reporting the marker alone calls
/// a working device "not connected", which is exactly how a phone that was in
/// fact syncing looked broken.
Future<bool> isFirebaseConfigured() async {
try {
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
);
if (await auth.hasSession()) return true;
// storedAccount, not loadAccount: on Android the latter falls back to the
// desktop wrapper's /sync-account route, which resolves to file:/// and
// throws "No host specified in URI" -- observed on the phone, where it
// turned a successful sign-in into "Google sign-in failed".
if (await storedAccount() == null) return false;
// A marker with no session behind it cannot sign a single request. Drop
// just the marker so the settings screen offers a sign-in instead of a
// dead banner -- not clearAccount(), which also sets the opt-out flag and
// would stop the desktop wrapper re-provisioning after the next sign-in.
await _secure.delete(key: kFirebaseAccountKey);
return false;
} on Object catch (error, stackTrace) {
log(
'session probe failed; reporting this device as not configured',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return false;
}
}
/// Returns a client built from the keystore's refresh token alone, or null.
///
/// The recovery path for a device that has a live session but no account
/// marker -- the state a Google sign-in used to leave behind. Costs one
/// keystore read and no network round trip when there is no session, so it is
/// safe on the background-tick path [openFirebase] also serves.
Future<FirebaseRestClient?> _clientFromStoredSession() async {
try {
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
);
if (!await auth.hasSession()) return null;
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
} on Object catch (error, stackTrace) {
log(
'stored-session recovery failed; falling back to the GitHub mirror',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return null;
}
}
// coverage:ignore-end

View File

@ -0,0 +1,11 @@
/// Platform gate for the programmatic Google sign-in flow.
///
/// Conditional export because the answer differs per platform *and* because
/// asking the plugin directly is unsafe: `supportsAuthenticate()` throws
/// `UnimplementedError` where no implementation is registered -- an `Error`,
/// not an `Exception`, so it escapes an ordinary catch and would take down
/// the settings screen's `build()`.
library;
export 'google_platform_io.dart'
if (dart.library.js_interop) 'google_platform_web.dart';

View File

@ -0,0 +1,10 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The io half: Android has the Credential Manager flow; Linux desktop does
/// not, and this app's desktop build is the web one anyway.
library;
import 'dart:io';
/// True only on Android, the one platform shipping the programmatic flow.
bool get googleSignInSupported => Platform.isAndroid;

View File

@ -0,0 +1,8 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The web half: Google Identity Services signs in only through its own
/// rendered button, so `authenticate()` throws `UnimplementedError` here.
library;
/// Always false: the web plugin has no programmatic sign-in.
bool get googleSignInSupported => false;

View File

@ -0,0 +1,122 @@
/// One-tap Google sign-in, kept apart from the rest of the sync wiring.
///
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
/// `crypto` and `http`), because the same library runs on Linux desktop and
/// headless under systemd, where `google_sign_in` does not exist. So the
/// plugin lives here, in the app, and the library only ever receives a token
/// string through a closure.
///
/// What this buys: on a fresh install the sync account is reached by tapping
/// one account-picker row instead of typing a long password on a phone
/// keyboard. The password path stays as the fallback and as the machine
/// credential for desktop and the Python side.
library;
import 'dart:developer';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:workout_app/services/google_platform.dart' as platform_gate;
/// The account the security rules pin.
///
/// Not a secret -- it is already in the public `database.rules.json` -- but it
/// is the value that makes a wrong-account sign-in *fail loudly* instead of
/// authenticating fine and then being denied every read and write. See
/// `crdt-sync/tool/link_google.py`, which is what put the Google identity on
/// this uid in the first place.
const kSyncUid = 'OvA2REQyLIhAHOEjzwS1o877rgG3';
/// The project's **Web** OAuth client id, used as the audience for ID
/// tokens.
///
/// Public by design, exactly like [kProject]'s `apiKey`: it ships inside every
/// APK, and the security rules -- not its secrecy -- protect the data.
///
/// A plain const rather than a `--dart-define`, deliberately. As a
/// compile-time environment value it was empty in every build that matters:
/// the phone-deploy skill and CI both run a bare `flutter build apk
/// --release`, so released APKs would have shown a Google button that always
/// reported "cancelled" -- a visible control that can never succeed, which is
/// the exact thing the web platform gate exists to prevent.
///
/// Fill this in from Firebase console -> Project settings -> the `syncs-rest`
/// Web app's OAuth client (type "Web application"). Android must request a
/// token minted for the *web* client; an Android client id here yields a token
/// Firebase rejects with `audience mismatch`.
/// Empty until the Web OAuth client is registered; [googleSignInSupported] is
/// false while it is, so the button stays hidden rather than failing.
const kServerClientId =
'845446124781-prdoherj0v64vc6egvvcp3l0693khaur.apps.googleusercontent.com';
/// Whether this platform can sign in programmatically.
///
/// False on web, where Google Identity Services only signs in through its own
/// rendered button: `authenticate()` throws `UnimplementedError` there. The
/// desktop build of this app *is* the web build, so without this check the
/// "Sign in with Google" button would crash the settings screen on desktop
/// rather than falling back; see `google_platform.dart` for why this is a
/// platform check rather than a question asked of the plugin.
///
/// Also false when no client id is compiled in: a button that cannot possibly
/// succeed is worse than no button, and without this check an unconfigured
/// build reports "cancelled" and sends you debugging the OAuth console for a
/// problem that is really a missing constant.
bool get googleSignInSupported =>
platform_gate.googleSignInSupported && kServerClientId.isNotEmpty;
/// Returns a Google ID token for the signed-in account, or null.
///
/// Null rather than throwing when the user dismisses the picker: cancelling is
/// an ordinary outcome, and the caller falls back to the password path.
///
/// [signInFn] and [serverClientId] exist for tests, which cannot reach the
/// platform channel the plugin uses.
Future<String?> googleIdToken({
Future<String?> Function()? signInFn,
String serverClientId = kServerClientId,
}) async {
if (signInFn != null) return signInFn();
if (serverClientId.isEmpty) {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
// fail inside the plugin with a far less obvious message.
log(
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
'build time; falling back to the password path',
level: 900,
);
return null;
}
// The plugin reaches the OS account picker through a platform channel,
// which `flutter test` has no binding for -- the same reason main.dart and
// firebase_backend.dart's keystore adapters are excluded. Everything above
// this point is pure Dart and is covered.
// coverage:ignore-start
try {
await GoogleSignIn.instance.initialize(serverClientId: serverClientId);
if (!GoogleSignIn.instance.supportsAuthenticate()) {
// Web/desktop: sign-in must go through the rendered GIS button, which
// this app does not host yet. Fall back rather than throwing.
log(
'Google sign-in is not available on this platform; falling back to '
'the password path',
level: 900,
);
return null;
}
final account = await GoogleSignIn.instance.authenticate();
return account.authentication.idToken;
} on GoogleSignInException catch (error, stackTrace) {
// Includes the user simply dismissing the picker, which is not an error
// worth surfacing -- but log it, because a *configuration* failure
// (unregistered SHA-1, wrong client id) arrives through the same path and
// is otherwise indistinguishable from "the user changed their mind".
log(
'Google sign-in did not complete',
level: 900,
error: error,
stackTrace: stackTrace,
);
return null;
}
// coverage:ignore-end
}

View File

@ -141,11 +141,11 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.9.0"
resolved-ref: f902bbe0aa6689adbe4ef0ef6bb298655f4e136a
ref: "crdt_sync_dart-v0.10.0"
resolved-ref: "5f64a8959b1db342da1f73157b1148aa0dfa38a8"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.9.0"
version: "0.10.0"
crypto:
dependency: transitive
description:
@ -297,6 +297,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.3"
google_identity_services_web:
dependency: transitive
description:
name: google_identity_services_web
sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454"
url: "https://pub.dev"
source: hosted
version: "0.3.3+1"
google_sign_in:
dependency: "direct main"
description:
name: google_sign_in
sha256: "521031b65853b4409b8213c0387d57edaad7e2a949ce6dea0d8b2afc9cb29763"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
google_sign_in_android:
dependency: transitive
description:
name: google_sign_in_android
sha256: "57782125965ca87b03d42a147d40b046f1fd6a09141a58913e1b86671a5ef22e"
url: "https://pub.dev"
source: hosted
version: "7.2.16"
google_sign_in_ios:
dependency: transitive
description:
name: google_sign_in_ios
sha256: ac1e4c1205267cb7999d1d81333fccffdfda29e853f434bbaf71525498bb6950
url: "https://pub.dev"
source: hosted
version: "6.3.0"
google_sign_in_platform_interface:
dependency: transitive
description:
name: google_sign_in_platform_interface
sha256: "7f59208c42b415a3cca203571128d6f84f885fead2d5b53eb65a9e27f2965bb5"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
google_sign_in_web:
dependency: transitive
description:
name: google_sign_in_web
sha256: d473003eeca892f96a01a64fc803378be765071cb0c265ee872c7f8683245d14
url: "https://pub.dev"
source: hosted
version: "1.1.3"
hooks:
dependency: transitive
description:

View File

@ -12,11 +12,15 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.9.0
ref: crdt_sync_dart-v0.10.0
path: crdt_sync_dart
flutter:
sdk: flutter
flutter_secure_storage: ^10.3.1
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
# Dart so it keeps working on Linux desktop and headless.
google_sign_in: ^7.2.0
http: ^1.6.0
path: ^1.9.1
path_provider: ^2.1.5

View File

@ -0,0 +1,88 @@
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
import 'fake_secure_storage.dart';
/// Answers a `signInWithIdp` call the way Firebase does.
http_testing.MockClient _signsInAs(String email, {String uid = kSyncUid}) =>
http_testing.MockClient(
(request) async => http.Response(
jsonEncode({
'idToken': 'id',
'refreshToken': 'refresh',
'expiresIn': '3600',
'email': email,
'localId': uid,
}),
200,
),
);
void main() {
// installFakeSecureStorage touches the test binary messenger, which only
// exists once the binding is initialised.
TestWidgetsFlutterBinding.ensureInitialized();
// openFirebaseWithGoogle reaches the keystore through a platform channel;
// the fake stands in so the account write is really exercised rather than
// stubbed out at the call site.
setUp(installFakeSecureStorage);
group('openFirebaseWithGoogle', () {
test('returns null when the picker is dismissed', () async {
// Cancelling is ordinary: no session, no account, no error.
final saved = <FirebaseAccount>[];
final client = await openFirebaseWithGoogle(
tokenFetcher: () async => null,
accountSaver: (account) async => saved.add(account),
);
expect(client, isNull);
expect(saved, isEmpty);
});
test('stores the account under the email Firebase reports', () async {
// The regression this test exists for. A fresh install has no email
// anywhere on the device, so it must come from the sign-in response. An
// earlier cut read it from the settings screen's text field -- empty on
// exactly this path -- and persisted FirebaseAccount(email: ''); the
// next launch then took the password branch with '' and failed.
final saved = <FirebaseAccount>[];
final client = await openFirebaseWithGoogle(
tokenFetcher: () async => 'a-token',
accountSaver: (account) async => saved.add(account),
httpClient: _signsInAs('signed-in@example.com'),
);
expect(client, isNotNull);
expect(saved, hasLength(1));
expect(saved.single.email, 'signed-in@example.com');
// No password to store: this device authenticates with the refresh
// token, and openFirebase() must not later try to sign in with ''.
expect(saved.single.password, isEmpty);
client!.close();
});
test('stores nothing when Google resolves to the wrong uid', () async {
// Authentication succeeds and the uid is wrong, which the security
// rules would deny on every read and write. Failing here -- with
// nothing persisted -- leaves the device retryable rather than stuck.
final saved = <FirebaseAccount>[];
await expectLater(
openFirebaseWithGoogle(
tokenFetcher: () async => 'a-token',
accountSaver: (account) async => saved.add(account),
httpClient: _signsInAs('someone@example.com', uid: 'a-different-uid'),
),
throwsA(isA<FirebaseAuthError>()),
);
expect(saved, isEmpty);
});
});
}

View File

@ -0,0 +1,14 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
void main() {
test('reports whether the programmatic Google flow exists here', () {
// Android is the only platform shipping it. Asked as a platform question
// rather than of the plugin, because GoogleSignIn.supportsAuthenticate()
// itself throws UnimplementedError where no implementation is registered
// -- an Error, not an Exception, so it would escape an ordinary catch and
// take down the settings screen's build(). The test host is Linux, so
// this is false here and the password path stays visible.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -0,0 +1,13 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_platform_web.dart';
void main() {
test('the web half always reports the programmatic flow unsupported', () {
// The conditional export in google_platform.dart never pulls this file
// in on the Linux test host (it resolves to google_platform_io.dart
// instead), so it would otherwise never appear in coverage at all.
// Imported directly here for that reason, same pattern as
// sync_state_factory_web_test.dart elsewhere in this app family.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -0,0 +1,33 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
void main() {
group('googleIdToken', () {
test('returns the token the sign-in function yields', () async {
// The injected path: proves the closure is what feeds crdt_sync, and
// that no platform channel is touched to get there.
expect(
await googleIdToken(signInFn: () async => 'a-token'),
'a-token',
);
});
test('passes a null cancellation straight through', () async {
// Dismissing the picker is an ordinary outcome, not an error: the
// caller falls back to the password path.
expect(await googleIdToken(signInFn: () async => null), isNull);
});
test('reports "not configured" when the client id is missing', () async {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID must fall back
// rather than failing deep inside the plugin with an opaque message.
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('pins the uid the security rules expect', () {
// If this ever drifts from database.rules.json, a Google sign-in would
// be accepted here and then denied every read and write.
expect(kSyncUid, 'OvA2REQyLIhAHOEjzwS1o877rgG3');
});
});
}

View File

@ -65,9 +65,12 @@ void main() {
Widget _wrap({
http.Client? httpClient,
Future<FirebaseRestClient?> Function()? firebaseFactory,
Future<FirebaseRestClient?> Function()? googleFirebaseFactory,
bool? googleAvailable,
Future<FirebaseAccount?> Function()? accountLoader,
Future<void> Function(FirebaseAccount)? accountSaver,
Future<void> Function()? accountClearer,
Future<bool> Function()? sessionProbe,
Future<bool> Function()? storageChecker,
Future<bool> Function()? storageRequester,
Future<ProgressionSyncResult> Function()? progressionPuller,
@ -78,9 +81,19 @@ void main() {
// Injected so the widget never reaches the OS keystore, which
// `flutter test` has no platform-channel binding for.
firebaseFactory: firebaseFactory ?? () async => null,
googleFirebaseFactory: googleFirebaseFactory,
googleAvailable: googleAvailable,
accountLoader: accountLoader ?? () async => null,
accountSaver: accountSaver,
accountClearer: accountClearer,
// Defaults to whatever the injected account says, so a test that only
// stubs the account still describes one coherent device. The production
// probe reads the keystore this harness deliberately avoids, and would
// otherwise answer "no session" for a device the test declared signed
// in.
sessionProbe:
sessionProbe ??
() async => await (accountLoader ?? () async => null)() != null,
// Same reason: permission_handler is a platform channel too.
storageChecker: storageChecker ?? () async => false,
storageRequester: storageRequester,
@ -329,6 +342,121 @@ void main() {
expect(find.text('sync@example.com'), findsOneWidget);
});
testWidgets(
'Sign in with Google connects and reads back the persisted account',
(tester) async {
var sessionStored = false;
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async {
sessionStored = true;
return _stubFirebaseClient();
},
accountLoader: () async => sessionStored
? const FirebaseAccount(email: 'g@example.com', password: '')
: null,
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.text('Connected to Firebase.'), findsOneWidget);
expect(find.text('g@example.com'), findsOneWidget);
},
);
testWidgets(
'Sign in with Google reports a cancelled picker as pending, not an error',
(tester) async {
await _pump(
tester,
_wrap(googleAvailable: true, googleFirebaseFactory: () async => null),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pump();
await tester.pump();
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
},
);
testWidgets(
'Sign in with Google that does not persist a session reports the retry '
'message',
(tester) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async => _stubFirebaseClient(),
sessionProbe: () async => false,
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(
find.textContaining('did not save the session'),
findsOneWidget,
);
},
);
testWidgets('Sign in with Google wrong-account error surfaces the message', (
tester,
) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async =>
throw FirebaseAuthError('wrong uid'),
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.text('wrong uid'), findsOneWidget);
});
testWidgets('Sign in with Google generic failure surfaces the error text', (
tester,
) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async => throw StateError('boom'),
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.textContaining('Google sign-in failed'), findsOneWidget);
});
testWidgets('connecting pulls progression down immediately', (tester) async {
// Regression: connecting is the NORMAL path after a reinstall, because the
// uninstall wipes the keystore and startup's pull therefore found no