Swap google_sign_in for google_account_token

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZ9CKZsNxtD5Jr9bYD
This commit is contained in:
Krzysztof Rudnicki 2026-11-10 16:48:04 +01:00
parent aaaecca3be
commit 23ad2e02b4
11 changed files with 95 additions and 164 deletions

View File

@ -32,8 +32,8 @@ File? _desktopCredentialFile() {
/// `crdt_sync` Python library) already keeps the sync account there as
/// `firebase.json` + `password`, both mode 600, so the desktop build reads
/// that rather than standing up a second credential the user would have to
/// enter and keep in step. It also sidesteps `google_sign_in`, which has no
/// Linux implementation at all.
/// enter and keep in step. It also sidesteps `google_account_token`, which is
/// Android-only.
///
/// Returns null when the files are absent or malformed; the caller then
/// reports the device as not connected, exactly as an empty keystore would.

View File

@ -2,7 +2,7 @@ part of 'firebase_backend.dart';
// The interactive Google sign-in path. Separate from the rest of the backend
// because it is the only piece that can raise UI, and because it is dead code
// on Linux desktop -- google_sign_in ships no Linux implementation, so the
// on Linux desktop -- google_account_token is Android-only, so the
// desktop build authenticates from the shared refresh token instead.
// coverage:ignore-start

View File

@ -1,11 +0,0 @@
/// 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

@ -1,10 +0,0 @@
/// 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

@ -1,8 +0,0 @@
/// 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

@ -2,9 +2,9 @@
///
/// 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.
/// headless under systemd, where no Google plugin exists. So the plugin
/// (`google_account_token`) is used 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
@ -14,8 +14,7 @@ library;
import 'dart:developer';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:workout_app/services/google_platform.dart' as platform_gate;
import 'package:google_account_token/google_account_token.dart' as plugin;
/// The account the security rules pin.
///
@ -37,7 +36,8 @@ const kSyncUid = 'OvA2REQyLIhAHOEjzwS1o877rgG3';
/// the phone-deploy skill and CI both run `flutter build apk --release`
/// with no defines, 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.
/// which is the exact thing the [googleSignInSupported] 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
@ -50,73 +50,43 @@ const kServerClientId =
/// 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.
/// Only Android has an AccountManager (the plugin's own gate). Web and the
/// Linux desktop build authenticate from the shared credential instead, so
/// the button must not exist there. The plugin's check is web-safe (no
/// `dart:io`).
///
/// 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;
plugin.googleAccountTokenSupported && 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.
/// [signInFn], [serverClientId] and [warn] exist for tests that bypass the
/// plugin or observe the log.
Future<String?> googleIdToken({
Future<String?> Function()? signInFn,
String serverClientId = kServerClientId,
void Function(String message)? warn,
}) async {
if (signInFn != null) return await 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;
// Repo rule: a guard that aborts work must say so. Without this the
// caller only sees "cancelled" and debugs the OAuth console instead.
const message =
'WorkoutApp: Google sign-in unavailable: the Web client id '
'(kServerClientId) is empty; falling back to the password path';
if (warn != null) {
warn(message);
} else {
log(message, level: 900);
}
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
return await plugin.googleIdToken(serverClientId: serverClientId);
}

View File

@ -602,54 +602,15 @@ 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:
google_account_token:
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"
path: google_account_token
ref: "google_account_token-v0.1.0"
resolved-ref: db70ba204d124c6eadf9b8808cd3d3b3e70363d1
url: "https://github.com/kuhyx/utils"
source: git
version: "0.1.0"
gsettings:
dependency: transitive
description:

View File

@ -41,9 +41,14 @@ dependencies:
flutter_secure_storage: 11.2.0
# GPS fixes, behind the PositionSource seam (lib/services/position_source).
geolocator: 14.1.2
# 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
# One-tap sign-in for the sync account (AccountManager ID token; no Play
# Services SDK in the APK). App-side only: crdt_sync stays pure Dart so it
# keeps working on Linux desktop and headless.
google_account_token:
git:
url: https://github.com/kuhyx/utils
ref: google_account_token-v0.1.0
path: google_account_token
http: 1.6.0
http_cache_file_store: 2.0.2
latlong2: 0.10.1

View File

@ -1,14 +0,0 @@
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

@ -1,13 +0,0 @@
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

@ -1,7 +1,19 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
const _channel = MethodChannel('dev.kuhy/google_account_token');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
tearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, null);
});
group('googleIdToken', () {
test('returns the token the sign-in function yields', () async {
// The injected path: proves the closure is what feeds crdt_sync, and
@ -19,15 +31,54 @@ void main() {
});
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.
// An empty id must not reach the OS account chooser.
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('warns loudly when the client id is empty', () async {
final warnings = <String>[];
expect(
await googleIdToken(serverClientId: '', warn: warnings.add),
isNull,
);
expect(warnings, hasLength(1));
expect(warnings.single, contains('kServerClientId'));
});
test('logs via dart:developer when no warn hook is given', () async {
// Default path (no seam): must not throw and must still return null.
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('asks the account-token plugin for the Web client id', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
Object? sent;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
sent = call.arguments;
return 'plugin-token';
});
expect(await googleIdToken(), 'plugin-token');
expect(sent, {'serverClientId': kServerClientId});
});
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');
});
});
group('googleSignInSupported', () {
test('is true on Android', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(googleSignInSupported, isTrue);
});
test('is false on Linux desktop, so the password path stays', () {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
expect(googleSignInSupported, isFalse);
});
});
}