mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-22 03:02:17 +01:00
Fix desktop Firebase sync: seed a Google-derived session, not a dead password
Some checks are pending
release-apk / release (APK) (push) Waiting to run
Some checks are pending
release-apk / release (APK) (push) Waiting to run
The account's password grant is retired fleet-wide (see link_google.py / seed_session.py in ~/utils/crdt-sync), so desktop's Firebase form could never have connected regardless of provisioning. Desktop-as-web can't use the in-browser Google Sign-In button either (google_platform_web.dart hard-codes googleSignInSupported = false), so it needs the same session-seeding path the Python daemons already use: seed_session.py now includes todo, and the wrapper's new /sync-credentials route serves that seeded session to loadAccount() once per launch, then closes for the rest of the process. Also stops the status line reporting a bare "Synced" while running over the GitHub mirror alone with Firebase disconnected -- SyncResult now carries firebaseConnected so the UI can say "GitHub-only (Firebase not connected)". Includes the prior session's Google Sign-In one-tap addition (google_sign_in_backend.dart and friends), which this builds on. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FPsyKQRX8ZwJpUqg37jp83
This commit is contained in:
parent
790c7947f2
commit
d316563015
@ -5,6 +5,15 @@ import 'dart:io';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// Route serving `todo`'s own seeded Firebase session (a `FirebaseCredentials`
|
||||
/// JSON blob), alongside [kSyncAccountPath]'s email/password pair.
|
||||
///
|
||||
/// `todo`-local rather than added to `crdt_sync_dart`: no other app in the
|
||||
/// fleet runs a desktop wrapper of its own, so a shared route would add
|
||||
/// surface area five other apps never use. Gated by the same
|
||||
/// [kSyncAccountEnvVar] as [kSyncAccountPath].
|
||||
const kSyncCredentialsPath = '/sync-credentials';
|
||||
|
||||
/// Local HTTP server backing the desktop app.
|
||||
///
|
||||
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder manages
|
||||
@ -30,12 +39,21 @@ class WrapperServer {
|
||||
required this.logPath,
|
||||
bool? serveSyncAccount,
|
||||
String? syncConfigDir,
|
||||
String? todoCredentialsPath,
|
||||
}) : serveSyncAccount =
|
||||
serveSyncAccount ??
|
||||
(Platform.environment[kSyncAccountEnvVar] ?? '').isNotEmpty,
|
||||
syncConfigDir =
|
||||
syncConfigDir ??
|
||||
p.join(Platform.environment['HOME'] ?? '', '.config', 'crdt-sync');
|
||||
p.join(Platform.environment['HOME'] ?? '', '.config', 'crdt-sync'),
|
||||
todoCredentialsPath =
|
||||
todoCredentialsPath ??
|
||||
p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'.config',
|
||||
'todo',
|
||||
'firebase_auth.json',
|
||||
);
|
||||
|
||||
/// Whether the sync-account route answers; off unless explicitly enabled.
|
||||
final bool serveSyncAccount;
|
||||
@ -43,6 +61,26 @@ class WrapperServer {
|
||||
/// Directory holding `firebase.json` and `password`.
|
||||
final String syncConfigDir;
|
||||
|
||||
/// Whether [kSyncCredentialsPath] has served a valid credential yet.
|
||||
///
|
||||
/// Flips to true after the first 200 and 404s every request after that,
|
||||
/// so a normal launch can self-provision with no env var to remember (see
|
||||
/// [_syncCredentials]) while the exposure window for a database-write
|
||||
/// credential stays "until the app finishes booting" rather than "for as
|
||||
/// long as the wrapper process runs". Independent of [serveSyncAccount]:
|
||||
/// that gate protects the legacy shared `/sync-account` route other apps'
|
||||
/// wrappers also serve, which stays opt-in.
|
||||
bool _todoCredentialsServed = false;
|
||||
|
||||
/// `todo`'s own seeded Firebase session, written by
|
||||
/// `crdt-sync/tool/seed_session.py --app todo` in the same
|
||||
/// `{id_token, refresh_token, expires_at}` shape every other app's
|
||||
/// credential cache uses. The account's password grant is retired
|
||||
/// fleet-wide (see `link_google.py`/`seed_session.py`), so unlike
|
||||
/// [syncConfigDir]'s `password` file this is the only thing that actually
|
||||
/// authenticates.
|
||||
final String todoCredentialsPath;
|
||||
|
||||
/// Directory holding the built Flutter web assets.
|
||||
final String webRoot;
|
||||
|
||||
@ -96,6 +134,9 @@ class WrapperServer {
|
||||
if (path == kSyncAccountPath) {
|
||||
return _syncAccount(request);
|
||||
}
|
||||
if (path == kSyncCredentialsPath) {
|
||||
return _syncCredentials(request);
|
||||
}
|
||||
return _static(request, path);
|
||||
}
|
||||
|
||||
@ -125,8 +166,9 @@ class WrapperServer {
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
return;
|
||||
}
|
||||
final email = (jsonDecode(await configFile.readAsString())
|
||||
as Map<String, dynamic>)['email'];
|
||||
final email =
|
||||
(jsonDecode(await configFile.readAsString())
|
||||
as Map<String, dynamic>)['email'];
|
||||
if (email is! String || email.isEmpty) {
|
||||
stderr.writeln('firebase.json has no usable "email" — not serving it.');
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
@ -141,6 +183,78 @@ class WrapperServer {
|
||||
);
|
||||
}
|
||||
|
||||
/// Serves `todo`'s own seeded Firebase session, so a fresh desktop install
|
||||
/// can authenticate without ever seeing a password field and without a
|
||||
/// human setting an env var first.
|
||||
///
|
||||
/// Reachable by default (unlike [_syncAccount], which stays behind
|
||||
/// [serveSyncAccount]/[kSyncAccountEnvVar]) but only until the first
|
||||
/// successful serve: this hands out a credential with database write
|
||||
/// access to anything that can reach the port, shared with five other
|
||||
/// apps, so the window it is actually reachable in must be as small as
|
||||
/// "until the app finishes booting", not "for as long as the wrapper
|
||||
/// runs". 404 (not 403) both when already served and when disabled, so a
|
||||
/// probe cannot tell which case it hit.
|
||||
///
|
||||
/// Consumed once by `loadAccount()`'s wrapper fallback and written
|
||||
/// straight into the keystore; never a standing source the app re-reads on
|
||||
/// every launch. That matters here specifically: `seed_session.py` may
|
||||
/// later rotate this file's refresh token for an unrelated app's re-seed
|
||||
/// run, and Firebase invalidates the previous token when it does --
|
||||
/// serving a stale token to a device that already adopted the live one
|
||||
/// would just hand back a token neither side can use.
|
||||
Future<void> _syncCredentials(HttpRequest request) async {
|
||||
if (_todoCredentialsServed) {
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
return;
|
||||
}
|
||||
final credentialsFile = File(todoCredentialsPath);
|
||||
if (!credentialsFile.existsSync()) {
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
return;
|
||||
}
|
||||
final Map<String, dynamic> credentials;
|
||||
try {
|
||||
credentials =
|
||||
jsonDecode(await credentialsFile.readAsString())
|
||||
as Map<String, dynamic>;
|
||||
} on FormatException {
|
||||
stderr.writeln(
|
||||
'$todoCredentialsPath is not valid JSON — not serving it.',
|
||||
);
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
return;
|
||||
}
|
||||
if (credentials['id_token'] is! String ||
|
||||
credentials['refresh_token'] is! String ||
|
||||
credentials['expires_at'] is! String) {
|
||||
stderr.writeln(
|
||||
'$todoCredentialsPath is missing id_token/refresh_token/expires_at '
|
||||
'— not serving it.',
|
||||
);
|
||||
request.response.statusCode = HttpStatus.notFound;
|
||||
return;
|
||||
}
|
||||
// The email is a display nicety (so Settings shows an address instead of
|
||||
// a blank), not a credential -- read from the shared config, not from
|
||||
// todoCredentialsPath, which has no email field of its own.
|
||||
String? email;
|
||||
final configFile = File(p.join(syncConfigDir, 'firebase.json'));
|
||||
if (configFile.existsSync()) {
|
||||
final config =
|
||||
jsonDecode(await configFile.readAsString()) as Map<String, dynamic>;
|
||||
final configEmail = config['email'];
|
||||
if (configEmail is String && configEmail.isNotEmpty) {
|
||||
email = configEmail;
|
||||
}
|
||||
}
|
||||
request.response.headers.contentType = ContentType.json;
|
||||
request.response.write(jsonEncode({...credentials, 'email': email}));
|
||||
// After, not before writing the response: a request that fails partway
|
||||
// through must remain retryable rather than burning the one serve.
|
||||
_todoCredentialsServed = true;
|
||||
}
|
||||
|
||||
/// GET returns the file's contents (404 when absent); POST overwrites it.
|
||||
Future<void> _file(HttpRequest request, String filePath) async {
|
||||
final file = File(filePath);
|
||||
|
||||
@ -12,9 +12,13 @@
|
||||
/// half. On Android there is no such file.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
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:todo/desktop/wrapper_server.dart' show kSyncCredentialsPath;
|
||||
import 'package:todo/sync/google_sign_in_backend.dart';
|
||||
|
||||
/// The shared `kuhy-syncs` project.
|
||||
///
|
||||
@ -48,11 +52,20 @@ SecureCredentialStore credentialStore() => SecureCredentialStore(
|
||||
/// Reads the per-device account, or null when sync has not been set up.
|
||||
///
|
||||
/// Falls back to the local wrapper when the store is empty, so a desktop
|
||||
/// install can provision itself from `~/.config/crdt-sync/` instead of the
|
||||
/// account being retyped per machine. The fetched account is written to the
|
||||
/// store on first success, so the route is consulted once rather than being
|
||||
/// load-bearing forever.
|
||||
Future<FirebaseAccount?> loadAccount() async {
|
||||
/// install can provision itself instead of the account being retyped per
|
||||
/// machine. Tries the seeded Firebase session first (`/sync-credentials`,
|
||||
/// `~/.config/todo/firebase_auth.json` via `seed_session.py --app todo`) --
|
||||
/// the only thing that actually authenticates, since the shared account's
|
||||
/// password grant is retired fleet-wide (see `link_google.py`/
|
||||
/// `seed_session.py` in `~/utils/crdt-sync`) -- then the legacy
|
||||
/// email/password route (`/sync-account`, `~/.config/crdt-sync/`) as a
|
||||
/// fallback for a machine that has not been re-seeded yet. Whichever
|
||||
/// succeeds is written to the store on first success, so the route is
|
||||
/// consulted once rather than being load-bearing forever.
|
||||
///
|
||||
/// [httpClient] is injectable for tests; production opens and closes its own
|
||||
/// per attempted route.
|
||||
Future<FirebaseAccount?> loadAccount({http.Client? httpClient}) async {
|
||||
try {
|
||||
final stored = FirebaseAccount.tryParse(
|
||||
await _secure.read(key: kFirebaseAccountKey),
|
||||
@ -61,10 +74,20 @@ Future<FirebaseAccount?> loadAccount() async {
|
||||
// Disconnect must stick: without this the next launch would silently
|
||||
// re-adopt the account and the button would look broken.
|
||||
if (await _secure.read(key: kSyncAccountOptOutKey) != null) return null;
|
||||
final provisioned = await accountFromWrapper(Uri.base);
|
||||
final seeded = await _adoptCredentialsFromWrapper(
|
||||
Uri.base,
|
||||
client: httpClient,
|
||||
);
|
||||
if (seeded != null) return seeded;
|
||||
final provisioned = await accountFromWrapper(Uri.base, client: httpClient);
|
||||
if (provisioned != null) await saveAccount(provisioned);
|
||||
return provisioned;
|
||||
} on Exception catch (error, stackTrace) {
|
||||
// Broader than Exception on purpose: an Android build has no wrapper, so
|
||||
// `Uri.base` is `file:///` and accountFromWrapper raises an ArgumentError
|
||||
// ("No host specified in URI") -- an Error, which `on Exception` does not
|
||||
// catch. That escaped openFirebase() and killed the whole sync tick, so a
|
||||
// signed-in phone pulled nothing at all.
|
||||
} on Object catch (error, stackTrace) {
|
||||
// Still "not configured" rather than crashing the settings screen -- but
|
||||
// never silent: this hid *why* provisioning failed, which is
|
||||
// indistinguishable from "no account set" until you say so.
|
||||
@ -78,6 +101,54 @@ Future<FirebaseAccount?> loadAccount() async {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches `todo`'s seeded session from the wrapper's `/sync-credentials`
|
||||
/// route and adopts it: stores the refresh token in [credentialStore] and
|
||||
/// writes an account marker so the Settings screen shows an address instead
|
||||
/// of a blank. Returns the marker on success, null on any failure (route
|
||||
/// disabled, file absent, malformed body, no wrapper at all) -- the caller's
|
||||
/// fallback is simply "not configured".
|
||||
///
|
||||
/// [client] is injectable for tests; production opens and closes its own.
|
||||
Future<FirebaseAccount?> _adoptCredentialsFromWrapper(
|
||||
Uri base, {
|
||||
http.Client? client,
|
||||
}) async {
|
||||
final httpClient = client ?? http.Client();
|
||||
try {
|
||||
final response = await httpClient.get(base.resolve(kSyncCredentialsPath));
|
||||
if (response.statusCode != 200) return null;
|
||||
final body = jsonDecode(utf8.decode(response.bodyBytes));
|
||||
if (body is! Map<String, dynamic>) return null;
|
||||
if (body['id_token'] is! String ||
|
||||
body['refresh_token'] is! String ||
|
||||
body['expires_at'] is! String) {
|
||||
return null;
|
||||
}
|
||||
await credentialStore().save(FirebaseCredentials.fromJson(body));
|
||||
final email = body['email'];
|
||||
final account = FirebaseAccount(
|
||||
email: email is String ? email : '',
|
||||
password: '',
|
||||
);
|
||||
await saveAccount(account);
|
||||
return account;
|
||||
} on Exception {
|
||||
return null;
|
||||
} finally {
|
||||
if (client == null) httpClient.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 that only want to read back an
|
||||
/// account they just wrote — where a fallback would be wrong anyway — use
|
||||
/// this instead.
|
||||
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());
|
||||
@ -96,12 +167,142 @@ 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 passing googleIdToken here. This path runs from
|
||||
// background timers and, in some apps, before runApp -- offering Google
|
||||
// would let a non-interactive tick raise the OS account picker with no
|
||||
// user action behind it. Interactive sign-in goes through
|
||||
// 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 -- and on success the
|
||||
/// email is written to the keystore so every later launch takes the ordinary
|
||||
/// path.
|
||||
///
|
||||
/// Returns null when the user dismisses the picker or the token is refused;
|
||||
/// throws [FirebaseAuthError] when Google succeeds but resolves to the wrong
|
||||
/// uid, which is a misconfiguration worth surfacing rather than swallowing.
|
||||
///
|
||||
/// On success the account is written to the keystore using the email
|
||||
/// **Firebase reports**, not 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 ''.
|
||||
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.
|
||||
// password is empty on purpose: this device has a refresh token and no
|
||||
// password to store. loadAccount() treats the account as configured, and
|
||||
// openFirebase() re-signs-in with Google rather than with an empty
|
||||
// password -- see the googleIdToken argument it passes.
|
||||
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.
|
||||
///
|
||||
/// The marker alone is not enough, though. A revoked refresh token makes the
|
||||
/// library clear the session, and a marker left behind by the sign-in that
|
||||
/// created it would still report "Connected" while every sync failed with
|
||||
/// TOKEN_EXPIRED -- the desktop symptom seen on 2026-08-11. So when a marker
|
||||
/// exists but the session is gone, the marker is the stale half: drop it.
|
||||
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
|
||||
|
||||
11
lib/sync/google_platform.dart
Normal file
11
lib/sync/google_platform.dart
Normal 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';
|
||||
10
lib/sync/google_platform_io.dart
Normal file
10
lib/sync/google_platform_io.dart
Normal 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;
|
||||
8
lib/sync/google_platform_web.dart
Normal file
8
lib/sync/google_platform_web.dart
Normal 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;
|
||||
122
lib/sync/google_sign_in_backend.dart
Normal file
122
lib/sync/google_sign_in_backend.dart
Normal 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:todo/sync/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
|
||||
}
|
||||
@ -47,12 +47,13 @@ Future<SyncResult> runSync(
|
||||
stateStore: stateStore ?? await openSyncStateStore(),
|
||||
// coverage:ignore-end
|
||||
);
|
||||
return await service.sync(
|
||||
final result = await service.sync(
|
||||
repository,
|
||||
firebase == null
|
||||
? github
|
||||
: MirrorStore(primary: firebase, mirror: github),
|
||||
);
|
||||
return result.withFirebaseConnected(value: firebase != null);
|
||||
} finally {
|
||||
// Close both: unlike the long-lived desktop callers, each screen builds
|
||||
// these per run.
|
||||
|
||||
@ -10,6 +10,7 @@ class SyncResult {
|
||||
required this.pushed,
|
||||
this.skippedFiles = const [],
|
||||
this.skippedUnchanged = 0,
|
||||
this.firebaseConnected = false,
|
||||
});
|
||||
|
||||
/// How many other devices' logs were pulled and merged.
|
||||
@ -18,6 +19,17 @@ class SyncResult {
|
||||
/// Whether this device pushed its own log.
|
||||
final bool pushed;
|
||||
|
||||
/// Whether this run's primary backend was Firebase, rather than GitHub
|
||||
/// alone. Set by the caller ([runSync]), which is the only layer that
|
||||
/// knows which [RemoteStore] it built -- [SyncService] itself is
|
||||
/// deliberately agnostic to what [RemoteStore] it was handed.
|
||||
///
|
||||
/// Exists so the status line can say so: reporting a plain "Synced" while
|
||||
/// this is false is what made a desktop stuck on GitHub-only look
|
||||
/// identical to one actually reaching Firebase, on a device that had in
|
||||
/// fact never connected.
|
||||
final bool firebaseConnected;
|
||||
|
||||
/// Peer files that were listed but could not be fetched or decoded
|
||||
/// (vanished, corrupt, or foreign format) and were left out of the merge.
|
||||
/// Surfaced so a device silently dropping out of sync is visible.
|
||||
@ -29,10 +41,22 @@ class SyncResult {
|
||||
/// device dropping out.
|
||||
final int skippedUnchanged;
|
||||
|
||||
/// Returns a copy with [firebaseConnected] set. [SyncService] never sets
|
||||
/// it -- only [runSync], which is the layer that knows which [RemoteStore]
|
||||
/// it built -- so this is the seam that lets it do that without
|
||||
/// [SyncService] taking on knowledge of Firebase at all.
|
||||
SyncResult withFirebaseConnected({required bool value}) => SyncResult(
|
||||
mergedDevices: mergedDevices,
|
||||
pushed: pushed,
|
||||
skippedFiles: skippedFiles,
|
||||
skippedUnchanged: skippedUnchanged,
|
||||
firebaseConnected: value,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'SyncResult(mergedDevices: $mergedDevices, pushed: $pushed, '
|
||||
'skippedFiles: $skippedFiles)';
|
||||
'firebaseConnected: $firebaseConnected, skippedFiles: $skippedFiles)';
|
||||
}
|
||||
|
||||
/// Synchronises a [NoteRepository] with a GitHub repo used as dumb storage.
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
|
||||
import 'dart:async';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@ -186,9 +185,19 @@ class _CaptureScreenState extends State<CaptureScreen>
|
||||
/// Human-readable one-liner for a sync outcome, shared by the snackbar and
|
||||
/// the status line. Skipped files are called out so a peer device silently
|
||||
/// dropping out of the merge is visible.
|
||||
///
|
||||
/// Firebase-vs-GitHub-only is called out too, and first, because it used
|
||||
/// to read identically either way: "Synced ... merged N device(s))" while
|
||||
/// disconnected from Firebase looked exactly like success, which is
|
||||
/// precisely how a desktop stuck syncing over the GitHub mirror alone
|
||||
/// went unnoticed for days.
|
||||
static String _describe(SyncResult result) {
|
||||
final skipped = result.skippedFiles.length;
|
||||
return 'merged ${result.mergedDevices} device(s)'
|
||||
final backend = result.firebaseConnected
|
||||
? ''
|
||||
: 'GitHub-only (Firebase not connected) — ';
|
||||
return '$backend'
|
||||
'merged ${result.mergedDevices} device(s)'
|
||||
'${skipped == 0 ? '' : ', skipped $skipped unreadable file(s)'}';
|
||||
}
|
||||
|
||||
|
||||
@ -9,6 +9,7 @@ import 'package:todo/data/note_repository.dart';
|
||||
import 'package:todo/sync/backlog_export.dart';
|
||||
import 'package:todo/sync/firebase_backend.dart';
|
||||
import 'package:todo/sync/github_device_auth.dart';
|
||||
import 'package:todo/sync/google_sign_in_backend.dart';
|
||||
import 'package:todo/sync/notes_markdown.dart';
|
||||
import 'package:todo/sync/run_sync.dart';
|
||||
import 'package:todo/sync/sync_settings.dart';
|
||||
@ -31,10 +32,13 @@ class SettingsScreen extends StatefulWidget {
|
||||
required this.repository,
|
||||
this.httpClient,
|
||||
this.firebaseFactory,
|
||||
this.googleFirebaseFactory,
|
||||
this.googleAvailable,
|
||||
this.stateStore,
|
||||
this.accountLoader,
|
||||
this.accountSaver,
|
||||
this.accountClearer,
|
||||
this.sessionProbe,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@ -48,6 +52,16 @@ class SettingsScreen extends StatefulWidget {
|
||||
/// null to assert the pre-migration GitHub-only path still works.
|
||||
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
|
||||
/// actually supports; injected by tests, which run on a host where the
|
||||
/// plugin reports unsupported.
|
||||
final bool? googleAvailable;
|
||||
|
||||
/// Revision cache. Injected so tests need no application-support directory.
|
||||
final SyncStateStore? stateStore;
|
||||
|
||||
@ -63,6 +77,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;
|
||||
|
||||
/// Optional HTTP client for the GitHub calls (test-connection and device
|
||||
/// flow). Injected by tests; production uses each client's default.
|
||||
final http.Client? httpClient;
|
||||
@ -103,9 +126,13 @@ 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) _email.text = account.email;
|
||||
setState(() => _firebaseConnected = account != null);
|
||||
setState(() => _firebaseConnected = connected);
|
||||
}
|
||||
|
||||
/// Stores the typed account and signs in immediately, so a typo surfaces
|
||||
@ -146,6 +173,75 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Signs in by picking a Google account -- the one-tap path.
|
||||
///
|
||||
/// Distinguishes three outcomes deliberately: a dismissed picker is not an
|
||||
/// error and says nothing alarming; a wrong-account sign-in reports *why*,
|
||||
/// because it is the failure that would otherwise look like a working sync
|
||||
/// that never syncs; anything else is a plain failure.
|
||||
Future<void> _connectGoogle() async {
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_status = 'Signing in…';
|
||||
});
|
||||
try {
|
||||
final client =
|
||||
await (widget.googleFirebaseFactory ?? openFirebaseWithGoogle)();
|
||||
if (!mounted) return;
|
||||
if (client == null) {
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_status = 'Google sign-in was cancelled.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
// The account is saved by openFirebaseWithGoogle, using the email
|
||||
// Firebase reports -- not from _email, which is empty on the fresh
|
||||
// install this path exists for. Reflect it so the connected row shows
|
||||
// the address instead of a blank.
|
||||
//
|
||||
// storedAccount, not loadAccount: the latter falls back to the desktop
|
||||
// wrapper's /sync-account route when the keystore looks empty, which on
|
||||
// Android resolves to file:/// and throws. That threw here mid-sign-in
|
||||
// on the phone, leaving the screen stuck on "Signing in..." even though
|
||||
// the sign-in had actually succeeded.
|
||||
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) _email.text = account.email;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_firebaseConnected = connected;
|
||||
_status = 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.';
|
||||
});
|
||||
} on FirebaseAuthError catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_firebaseConnected = false;
|
||||
_status = error.message;
|
||||
});
|
||||
} 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 on "Signing in..." forever -- which is exactly what
|
||||
// happened on the phone. Always land in a state the user can retry from.
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_firebaseConnected = false;
|
||||
_status = 'Google sign-in failed: $error';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disconnectFirebase() async {
|
||||
await (widget.accountClearer ?? clearAccount)();
|
||||
if (!mounted) return;
|
||||
@ -350,33 +446,64 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
],
|
||||
)
|
||||
else ...[
|
||||
TextField(
|
||||
controller: _email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Sync account email',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _password,
|
||||
obscureText: true,
|
||||
autocorrect: false,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Sync account password',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _busy ? null : _connectFirebase,
|
||||
icon: const Icon(Icons.cloud_done),
|
||||
label: const Text('Connect Firebase'),
|
||||
// The whole point of this screen after a reinstall: one tap, no
|
||||
// typing. The password form is kept but demoted, because on a
|
||||
// phone keyboard it is the slow path.
|
||||
//
|
||||
// Hidden where the platform cannot sign in programmatically --
|
||||
// the desktop build is the web build, and Google Identity
|
||||
// Services only signs in through its own rendered button there.
|
||||
// A visible button that always failed would be worse than none.
|
||||
if (widget.googleAvailable ?? googleSignInSupported) ...[
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _busy ? null : _connectGoogle,
|
||||
icon: const Icon(Icons.account_circle),
|
||||
label: const Text('Sign in with Google'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
ExpansionTile(
|
||||
// Expanded by default where Google is unavailable: on desktop
|
||||
// the password form is the only way in, so hiding it behind a
|
||||
// disclosure would look like there is no way to connect.
|
||||
initiallyExpanded:
|
||||
!(widget.googleAvailable ?? googleSignInSupported),
|
||||
title: const Text('Use the account password instead'),
|
||||
tilePadding: EdgeInsets.zero,
|
||||
childrenPadding: const EdgeInsets.only(bottom: 8),
|
||||
children: [
|
||||
TextField(
|
||||
controller: _email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Sync account email',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _password,
|
||||
obscureText: true,
|
||||
autocorrect: false,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Sync account password',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _busy ? null : _connectFirebase,
|
||||
icon: const Icon(Icons.cloud_done),
|
||||
label: const Text('Connect Firebase'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
|
||||
54
pubspec.lock
54
pubspec.lock
@ -101,11 +101,11 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: crdt_sync_dart
|
||||
ref: "crdt_sync_dart-v0.8.0"
|
||||
resolved-ref: "6a080333c2ed2b2773fee01605dd67ba713e54ea"
|
||||
ref: "crdt_sync_dart-v0.10.0"
|
||||
resolved-ref: "5f64a8959b1db342da1f73157b1148aa0dfa38a8"
|
||||
url: "https://github.com/kuhyx/utils"
|
||||
source: git
|
||||
version: "0.8.0"
|
||||
version: "0.10.0"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -321,6 +321,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:
|
||||
|
||||
10
pubspec.yaml
10
pubspec.yaml
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.4+1
|
||||
version: 1.0.5+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
@ -33,7 +33,7 @@ dependencies:
|
||||
crdt_sync:
|
||||
git:
|
||||
url: https://github.com/kuhyx/utils
|
||||
ref: crdt_sync_dart-v0.8.0
|
||||
ref: crdt_sync_dart-v0.10.0
|
||||
path: crdt_sync_dart
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
@ -46,6 +46,11 @@ dependencies:
|
||||
# Stores the GitHub sync token in the OS keystore (Android Keystore /
|
||||
# libsecret) instead of plaintext SharedPreferences.
|
||||
flutter_secure_storage: ^10.3.1
|
||||
|
||||
# One-tap sign-in for the sync account. Lives only in the app: `crdt_sync`
|
||||
# stays pure Dart so it keeps working on Linux desktop and headless, where
|
||||
# this plugin does not exist. See lib/sync/google_sign_in_backend.dart.
|
||||
google_sign_in: ^7.2.0
|
||||
http: ^1.6.0
|
||||
idb_shim: ^2.9.6+2
|
||||
path: ^1.9.1
|
||||
@ -132,3 +137,4 @@ flutter_launcher_icons:
|
||||
adaptive_icon_foreground: "assets/icon/icon_foreground.png"
|
||||
adaptive_icon_monochrome: "assets/icon/icon_monochrome.png"
|
||||
min_sdk_android: 21
|
||||
|
||||
|
||||
88
scripts/check_no_crdt_sync_override.sh
Executable file
88
scripts/check_no_crdt_sync_override.sh
Executable file
@ -0,0 +1,88 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Fail if a pubspec still overrides crdt_sync with a local path.
|
||||
#
|
||||
# The apps depend on crdt_sync as a *git dependency pinned to a tag*, so what
|
||||
# CI builds is whatever that tag points at. A `dependency_overrides:` entry
|
||||
# pointing at ~/utils/crdt_sync_dart is invaluable while developing an unreleased
|
||||
# library change -- and catastrophic if it survives the commit: local tests go
|
||||
# green against code CI has never seen, and the failure is silent in both
|
||||
# directions.
|
||||
#
|
||||
# A comment in the pubspec asking someone to remember is deployment hygiene,
|
||||
# not a fix. This is the gate.
|
||||
#
|
||||
# Usage: check_no_crdt_sync_override.sh [pubspec.yaml ...]
|
||||
# With no arguments, checks ./pubspec.yaml.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
readonly SCRIPT_NAME
|
||||
|
||||
usage() {
|
||||
echo "Usage: $SCRIPT_NAME [pubspec.yaml ...]"
|
||||
echo " Fails when a pubspec overrides crdt_sync with a local path."
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Returns 0 (found) when the file has a crdt_sync entry under
|
||||
# dependency_overrides. Deliberately a small state machine rather than a grep:
|
||||
# `path:` appears under plenty of other keys, and a false positive here blocks
|
||||
# a legitimate commit.
|
||||
has_override() {
|
||||
local file="$1"
|
||||
awk '
|
||||
# Track indent depth explicitly. An earlier version used an awk
|
||||
# interval expression ({1,4}) to spot a sibling key, which plain awk
|
||||
# does not enable by default -- so the check silently never fired and
|
||||
# reported every file clean. A safety check that fails open is worse
|
||||
# than none, so this version is written to be obvious instead of terse.
|
||||
function indent(line, n) {
|
||||
n = match(line, /[^ ]/)
|
||||
return (n == 0) ? 0 : n - 1
|
||||
}
|
||||
/^[[:space:]]*#/ { next } # comments
|
||||
/^[[:space:]]*$/ { next } # blank lines
|
||||
/^dependency_overrides:[[:space:]]*$/ { in_overrides = 1; next }
|
||||
/^[^[:space:]]/ { in_overrides = 0; in_crdt = 0; next }
|
||||
in_overrides {
|
||||
if ($0 ~ /^[[:space:]]+crdt_sync:[[:space:]]*$/) {
|
||||
in_crdt = 1
|
||||
crdt_indent = indent($0)
|
||||
next
|
||||
}
|
||||
# Any key at or above crdt_sync{s} own indent ends its block.
|
||||
if (in_crdt && indent($0) <= crdt_indent) { in_crdt = 0 }
|
||||
if (in_crdt && $0 ~ /^[[:space:]]+path:/) { found = 1 }
|
||||
}
|
||||
END { exit(found ? 0 : 1) }
|
||||
' "$file"
|
||||
}
|
||||
|
||||
main() {
|
||||
local -a files=("$@")
|
||||
if [[ ${#files[@]} -eq 0 ]]; then
|
||||
files=("pubspec.yaml")
|
||||
fi
|
||||
|
||||
local failed=0
|
||||
for file in "${files[@]}"; do
|
||||
[[ -f "$file" ]] || continue
|
||||
if has_override "$file"; then
|
||||
echo "Error: $file still has a local crdt_sync dependency_override." >&2
|
||||
echo " Remove it and bump the git 'ref:' to the released tag" >&2
|
||||
echo " before committing, or CI will build different code." >&2
|
||||
failed=1
|
||||
fi
|
||||
done
|
||||
return "$failed"
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
main "$@"
|
||||
@ -24,7 +24,12 @@ main() {
|
||||
#!/bin/bash
|
||||
# Installed by scripts/install_hooks.sh — see that file.
|
||||
set -euo pipefail
|
||||
exec bash "$(git rev-parse --show-toplevel)/scripts/bump_patch_version.sh"
|
||||
readonly ROOT="$(git rev-parse --show-toplevel)"
|
||||
# Gate first: a local crdt_sync override left in place makes CI build a
|
||||
# library this checkout has never tested against, silently and in both
|
||||
# directions. Blocking the commit is the only thing that actually prevents it.
|
||||
bash "$ROOT/scripts/check_no_crdt_sync_override.sh" "$ROOT/pubspec.yaml"
|
||||
exec bash "$ROOT/scripts/bump_patch_version.sh"
|
||||
HOOK_BODY
|
||||
|
||||
chmod 755 "$HOOK"
|
||||
|
||||
@ -235,7 +235,15 @@ void main() {
|
||||
await tester.pump(); // service runs, snackbar scheduled
|
||||
await tester.pump(); // snackbar builds
|
||||
|
||||
expect(find.textContaining('Synced: merged 0 device'), findsOneWidget);
|
||||
// No firebaseFactory was injected, so this runs over GitHub alone --
|
||||
// the status line must say so rather than reading identically to a
|
||||
// Firebase-connected sync.
|
||||
expect(
|
||||
find.textContaining(
|
||||
'Synced: GitHub-only (Firebase not connected) — merged 0 device',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Sync surfaces a failure from the sync service', (tester) async {
|
||||
|
||||
194
test/firebase_backend_test.dart
Normal file
194
test/firebase_backend_test.dart
Normal file
@ -0,0 +1,194 @@
|
||||
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:todo/sync/firebase_backend.dart';
|
||||
import 'package:todo/sync/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);
|
||||
});
|
||||
});
|
||||
|
||||
group('isFirebaseConfigured', () {
|
||||
// Regression (2026-08-11): the marker was checked first, so a device whose
|
||||
// refresh token had been revoked kept reporting "Connected" while every
|
||||
// sync failed with TOKEN_EXPIRED.
|
||||
test('is false when only a stale account marker survives', () async {
|
||||
await saveAccount(
|
||||
const FirebaseAccount(email: 'someone@example.com', password: 'pw'),
|
||||
);
|
||||
await credentialStore().clear();
|
||||
|
||||
expect(await isFirebaseConfigured(), isFalse);
|
||||
expect(
|
||||
await storedAccount(),
|
||||
isNull,
|
||||
reason: 'the stale marker must not be left behind',
|
||||
);
|
||||
});
|
||||
|
||||
test('is true when a session exists but the marker does not', () async {
|
||||
// The opposite failure: reporting the marker alone is what made a phone
|
||||
// that was in fact syncing look disconnected.
|
||||
await credentialStore().save(
|
||||
FirebaseCredentials(
|
||||
idToken: 'id',
|
||||
refreshToken: 'refresh',
|
||||
expiresAt: DateTime.now().toUtc().add(const Duration(hours: 1)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(await isFirebaseConfigured(), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('loadAccount', () {
|
||||
// The account's password grant is retired fleet-wide (see
|
||||
// link_google.py/seed_session.py in ~/utils/crdt-sync), so the wrapper's
|
||||
// seeded-credentials route is the only fallback that can actually
|
||||
// authenticate a fresh desktop install. These exercise loadAccount()'s
|
||||
// adoption of that route directly, since Uri.base in a test is
|
||||
// file:///, not a wrapper origin -- the same reason accountFromWrapper
|
||||
// itself needs an injected client to be testable at all.
|
||||
test('adopts seeded credentials from the wrapper', () async {
|
||||
final client = http_testing.MockClient((request) async {
|
||||
expect(request.url.path, '/sync-credentials');
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'id_token': 'id',
|
||||
'refresh_token': 'refresh',
|
||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||
'email': 'seeded@example.com',
|
||||
}),
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
final account = await loadAccount(httpClient: client);
|
||||
|
||||
expect(account?.email, 'seeded@example.com');
|
||||
expect(account?.password, isEmpty);
|
||||
expect(await credentialStore().load(), isNotNull);
|
||||
expect(await isFirebaseConfigured(), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'falls back to the account route when no credentials are served',
|
||||
() async {
|
||||
final client = http_testing.MockClient((request) async {
|
||||
if (request.url.path == '/sync-credentials') {
|
||||
return http.Response('', 404);
|
||||
}
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'email': 'password-account@example.com',
|
||||
'password': 'pw',
|
||||
}),
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
final account = await loadAccount(httpClient: client);
|
||||
|
||||
expect(account?.email, 'password-account@example.com');
|
||||
expect(account?.password, 'pw');
|
||||
},
|
||||
);
|
||||
|
||||
test('returns null when the wrapper serves neither route', () async {
|
||||
final client = http_testing.MockClient(
|
||||
(request) async => http.Response('', 404),
|
||||
);
|
||||
|
||||
expect(await loadAccount(httpClient: client), isNull);
|
||||
});
|
||||
|
||||
test('ignores a malformed credentials body', () async {
|
||||
final client = http_testing.MockClient((request) async {
|
||||
if (request.url.path == '/sync-credentials') {
|
||||
return http.Response(jsonEncode({'id_token': 'id'}), 200);
|
||||
}
|
||||
return http.Response('', 404);
|
||||
});
|
||||
|
||||
expect(await loadAccount(httpClient: client), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
33
test/google_sign_in_backend_test.dart
Normal file
33
test/google_sign_in_backend_test.dart
Normal file
@ -0,0 +1,33 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:todo/sync/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');
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -42,6 +42,10 @@ void main() {
|
||||
|
||||
expect(result.pushed, isTrue);
|
||||
expect(paths.every((p) => p.contains('api.github.com')), isTrue);
|
||||
// The status line's whole reason for existing: this must read as
|
||||
// GitHub-only, not as an unqualified success indistinguishable from a
|
||||
// Firebase-connected sync.
|
||||
expect(result.firebaseConnected, isFalse);
|
||||
});
|
||||
|
||||
test('makes Firebase primary and still mirrors to GitHub', () async {
|
||||
@ -91,5 +95,6 @@ void main() {
|
||||
contains('PUT'),
|
||||
reason: 'GitHub must still be mirrored during the cutover',
|
||||
);
|
||||
expect(result.firebaseConnected, isTrue);
|
||||
});
|
||||
}
|
||||
|
||||
@ -88,9 +88,12 @@ void main() {
|
||||
List<Note> seed = const [],
|
||||
FakeNoteRepository? repository,
|
||||
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,
|
||||
}) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
installFakeSecureStorage();
|
||||
@ -113,9 +116,19 @@ void main() {
|
||||
// real factories want the OS keystore and an application-support
|
||||
// directory, neither of which exists under `flutter test`.
|
||||
firebaseFactory: firebaseFactory ?? () async => null,
|
||||
googleFirebaseFactory: googleFirebaseFactory ?? () async => null,
|
||||
googleAvailable: googleAvailable ?? true,
|
||||
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 consults the keystore, which these tests fake
|
||||
// rather than provide, and would otherwise answer "no session" for
|
||||
// a device the test just declared signed in.
|
||||
sessionProbe:
|
||||
sessionProbe ??
|
||||
() async => await (accountLoader ?? () async => null)() != null,
|
||||
stateStore: InMemorySyncStateStore(),
|
||||
),
|
||||
),
|
||||
@ -124,6 +137,15 @@ void main() {
|
||||
return repo;
|
||||
}
|
||||
|
||||
/// Expands "Use the account password instead".
|
||||
///
|
||||
/// Google sign-in is the primary path now, so the email/password form is
|
||||
/// collapsed by default; a test that types credentials has to open it.
|
||||
Future<void> openPasswordForm(WidgetTester tester) async {
|
||||
await tester.tap(find.text('Use the account password instead'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Expands the "Advanced (GitHub mirror)" section.
|
||||
///
|
||||
/// GitHub is the cutover mirror rather than a choice the user makes, so
|
||||
@ -136,19 +158,32 @@ void main() {
|
||||
|
||||
testWidgets('renders sync fields and the backup actions', (tester) async {
|
||||
await pumpSettings(tester);
|
||||
// GitHub is the mirror now: hidden until the disclosure is opened.
|
||||
// GitHub is the mirror now: hidden until the disclosure is opened. The
|
||||
// password form is likewise behind one, leaving Google as the only
|
||||
// sign-in control on screen.
|
||||
expect(find.text('Connect GitHub'), findsNothing);
|
||||
expect(find.text('Connect Firebase'), findsOneWidget);
|
||||
expect(find.text('Connect Firebase'), findsNothing);
|
||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
||||
await openAdvanced(tester);
|
||||
expect(find.text('Connect GitHub'), findsOneWidget);
|
||||
expect(find.text('Export notes'), findsOneWidget);
|
||||
expect(find.text('Import notes'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('offers the Firebase account form when not connected', (
|
||||
testWidgets('offers Google first and the password form behind it', (
|
||||
tester,
|
||||
) async {
|
||||
// Ordering is the feature: after a reinstall the one-tap path has to be
|
||||
// the thing you see, with the phone-keyboard path available but demoted.
|
||||
await pumpSettings(tester);
|
||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
findsNothing,
|
||||
reason: 'the password form starts collapsed',
|
||||
);
|
||||
|
||||
await openPasswordForm(tester);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
findsOneWidget,
|
||||
@ -160,10 +195,93 @@ void main() {
|
||||
expect(find.text('Disconnect'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('hides Google and opens the password form on desktop', (
|
||||
tester,
|
||||
) async {
|
||||
// The desktop build is the web build, where Google Identity Services only
|
||||
// signs in through its own rendered button -- `authenticate()` throws
|
||||
// UnimplementedError there, and not a GoogleSignInException, so it would
|
||||
// not even have been caught. Offering a button that always crashed would
|
||||
// be worse than offering none, and the password form has to be visible
|
||||
// because it is then the only way in.
|
||||
await pumpSettings(tester, googleAvailable: false);
|
||||
|
||||
expect(find.text('Sign in with Google'), findsNothing);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
findsOneWidget,
|
||||
reason: 'the password form is expanded when it is the only option',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Sign in with Google connects without typing anything', (
|
||||
tester,
|
||||
) async {
|
||||
// The whole feature in one test: no text entered anywhere, one tap, and
|
||||
// the device ends up connected showing the account Google signed in as.
|
||||
//
|
||||
// The email comes from Firebase's response via openFirebaseWithGoogle,
|
||||
// not from the form -- a fresh install has nothing in the form, which is
|
||||
// exactly the scenario this path exists for. An earlier cut read the
|
||||
// controller here and persisted an empty account; the next launch then
|
||||
// took the password branch with '' and failed.
|
||||
// Starts genuinely unconfigured -- a fresh install -- and only gains an
|
||||
// account as a side effect of the Google sign-in itself.
|
||||
FirebaseAccount? stored;
|
||||
await pumpSettings(
|
||||
tester,
|
||||
googleFirebaseFactory: () async {
|
||||
stored = const FirebaseAccount(
|
||||
email: 'signed-in@example.com',
|
||||
password: '',
|
||||
);
|
||||
return _stubClient();
|
||||
},
|
||||
accountLoader: () async => stored,
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Sign in with Google'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Connected to Firebase.'), findsOneWidget);
|
||||
expect(find.text('signed-in@example.com'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a cancelled Google sign-in is not reported as an error', (
|
||||
tester,
|
||||
) async {
|
||||
// Dismissing the account picker is an ordinary thing to do; it must not
|
||||
// look like a failure.
|
||||
await pumpSettings(tester, googleFirebaseFactory: () async => null);
|
||||
|
||||
await tester.tap(find.text('Sign in with Google'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
|
||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a wrong-account Google sign-in explains itself', (tester) async {
|
||||
// The failure worth being loud about: authentication succeeds but the uid
|
||||
// is not the one the security rules pin, so every read and write would be
|
||||
// denied with no other symptom.
|
||||
await pumpSettings(
|
||||
tester,
|
||||
googleFirebaseFactory: () async =>
|
||||
throw FirebaseAuthError('signed in as the wrong account: uid X'),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Sign in with Google'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('wrong account'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Connect Firebase with empty fields asks for credentials', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpSettings(tester);
|
||||
await openPasswordForm(tester);
|
||||
await tester.tap(find.text('Connect Firebase'));
|
||||
await tester.pump();
|
||||
expect(
|
||||
@ -181,6 +299,7 @@ void main() {
|
||||
accountSaver: (a) async => saved = a,
|
||||
firebaseFactory: () async => _stubClient(),
|
||||
);
|
||||
await openPasswordForm(tester);
|
||||
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
@ -217,6 +336,7 @@ void main() {
|
||||
accountClearer: () async => cleared = true,
|
||||
firebaseFactory: () async => null,
|
||||
);
|
||||
await openPasswordForm(tester);
|
||||
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
@ -252,6 +372,10 @@ void main() {
|
||||
|
||||
expect(cleared, isTrue);
|
||||
expect(find.text('Firebase disconnected.'), findsOneWidget);
|
||||
// Back to the not-connected state, which now leads with Google rather
|
||||
// than with the email field.
|
||||
expect(find.text('Sign in with Google'), findsOneWidget);
|
||||
await openPasswordForm(tester);
|
||||
expect(
|
||||
find.widgetWithText(TextField, 'Sync account email'),
|
||||
findsOneWidget,
|
||||
|
||||
@ -83,6 +83,27 @@ void main() {
|
||||
expect(texts, contains('from other device'));
|
||||
});
|
||||
|
||||
test('withFirebaseConnected copies every other field unchanged', () {
|
||||
// SyncService itself never sets firebaseConnected -- only runSync does,
|
||||
// since SyncService is deliberately agnostic to which RemoteStore it was
|
||||
// handed. This is the seam that lets runSync attach that fact afterward.
|
||||
const original = SyncResult(
|
||||
mergedDevices: 2,
|
||||
pushed: true,
|
||||
skippedFiles: ['bad.json'],
|
||||
skippedUnchanged: 3,
|
||||
);
|
||||
|
||||
final connected = original.withFirebaseConnected(value: true);
|
||||
|
||||
expect(connected.firebaseConnected, isTrue);
|
||||
expect(connected.mergedDevices, original.mergedDevices);
|
||||
expect(connected.pushed, original.pushed);
|
||||
expect(connected.skippedFiles, original.skippedFiles);
|
||||
expect(connected.skippedUnchanged, original.skippedUnchanged);
|
||||
expect(connected.toString(), contains('firebaseConnected: true'));
|
||||
});
|
||||
|
||||
test('with no remote files, still pushes its own log', () async {
|
||||
final (:httpClient, :putCalls) = _mockGitHub(
|
||||
contentResponses: {'todo-sync/notes': _response(200, <Object>[])},
|
||||
|
||||
@ -34,6 +34,38 @@ void main() {
|
||||
root.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
/// Starts a second server with provisioning enabled against [files], and
|
||||
/// optionally a `todo`-specific credentials file at [credentialsJson].
|
||||
Future<String> enabledOrigin(
|
||||
Map<String, String> files, {
|
||||
String? credentialsJson,
|
||||
}) async {
|
||||
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
||||
..createSync(recursive: true);
|
||||
files.forEach((name, contents) {
|
||||
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
||||
});
|
||||
String? credentialsPath;
|
||||
if (credentialsJson != null) {
|
||||
final credentialsDir = Directory(p.join(root.path, 'todo-config'))
|
||||
..createSync(recursive: true);
|
||||
credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
||||
File(credentialsPath).writeAsStringSync(credentialsJson);
|
||||
}
|
||||
final enabled = WrapperServer(
|
||||
webRoot: p.join(root.path, 'web'),
|
||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||
serveSyncAccount: true,
|
||||
syncConfigDir: configDir.path,
|
||||
todoCredentialsPath:
|
||||
credentialsPath ?? p.join(root.path, 'todo-config', 'absent.json'),
|
||||
);
|
||||
await enabled.start(0);
|
||||
addTearDown(enabled.stop);
|
||||
return 'http://localhost:${enabled.port}';
|
||||
}
|
||||
|
||||
test('serves index.html at the root', () async {
|
||||
final response = await http.get(Uri.parse('$base/'));
|
||||
expect(response.statusCode, 200);
|
||||
@ -152,25 +184,6 @@ void main() {
|
||||
});
|
||||
|
||||
group('sync-account provisioning', () {
|
||||
/// Starts a second server with provisioning enabled against [files].
|
||||
Future<String> enabledOrigin(Map<String, String> files) async {
|
||||
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
||||
..createSync(recursive: true);
|
||||
files.forEach((name, contents) {
|
||||
File(p.join(configDir.path, name)).writeAsStringSync(contents);
|
||||
});
|
||||
final enabled = WrapperServer(
|
||||
webRoot: p.join(root.path, 'web'),
|
||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||
serveSyncAccount: true,
|
||||
syncConfigDir: configDir.path,
|
||||
);
|
||||
await enabled.start(0);
|
||||
addTearDown(enabled.stop);
|
||||
return 'http://localhost:${enabled.port}';
|
||||
}
|
||||
|
||||
test('is 404 when not enabled', () async {
|
||||
// The default, and the whole security posture: a credential route must
|
||||
// not be reachable just because the app is running.
|
||||
@ -212,4 +225,168 @@ void main() {
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
});
|
||||
|
||||
group('sync-credentials provisioning', () {
|
||||
// Unlike /sync-account, this route needs no CRDT_SYNC_SERVE_ACCOUNT: a
|
||||
// normal launch must self-provision with nothing to remember. [base]'s
|
||||
// server was built with no credentials file at the default path, so this
|
||||
// exercises the file-absent 404, not a disabled-route 404 -- there is no
|
||||
// "disabled" state for this route anymore.
|
||||
test(
|
||||
'is 404 when no credentials file exists at the default path',
|
||||
() async {
|
||||
final response = await http.get(
|
||||
Uri.parse('$base$kSyncCredentialsPath'),
|
||||
);
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
},
|
||||
);
|
||||
|
||||
test('serves once, then 404s for the rest of the process', () async {
|
||||
final credentialsDir = Directory(p.join(root.path, 'todo-config-once'))
|
||||
..createSync(recursive: true);
|
||||
final credentialsPath = p.join(credentialsDir.path, 'firebase_auth.json');
|
||||
File(credentialsPath).writeAsStringSync(
|
||||
jsonEncode({
|
||||
'id_token': 'id',
|
||||
'refresh_token': 'refresh',
|
||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
);
|
||||
final enabled = WrapperServer(
|
||||
webRoot: p.join(root.path, 'web'),
|
||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||
todoCredentialsPath: credentialsPath,
|
||||
);
|
||||
await enabled.start(0);
|
||||
addTearDown(enabled.stop);
|
||||
final origin = 'http://localhost:${enabled.port}';
|
||||
|
||||
final first = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
||||
final second = await http.get(Uri.parse('$origin$kSyncCredentialsPath'));
|
||||
|
||||
expect(first.statusCode, HttpStatus.ok);
|
||||
expect(second.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test(
|
||||
'serves the seeded credentials, with email from firebase.json',
|
||||
() async {
|
||||
final configDir = Directory(p.join(root.path, 'crdt-sync'))
|
||||
..createSync(recursive: true);
|
||||
File(
|
||||
p.join(configDir.path, 'firebase.json'),
|
||||
).writeAsStringSync('{"email":"seeded@example.com"}');
|
||||
final credentialsDir = Directory(p.join(root.path, 'todo-config'))
|
||||
..createSync(recursive: true);
|
||||
final credentialsPath = p.join(
|
||||
credentialsDir.path,
|
||||
'firebase_auth.json',
|
||||
);
|
||||
File(credentialsPath).writeAsStringSync(
|
||||
jsonEncode({
|
||||
'id_token': 'id',
|
||||
'refresh_token': 'refresh',
|
||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
);
|
||||
final enabled = WrapperServer(
|
||||
webRoot: p.join(root.path, 'web'),
|
||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||
serveSyncAccount: true,
|
||||
syncConfigDir: configDir.path,
|
||||
todoCredentialsPath: credentialsPath,
|
||||
);
|
||||
await enabled.start(0);
|
||||
addTearDown(enabled.stop);
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
||||
);
|
||||
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
|
||||
expect(response.statusCode, HttpStatus.ok);
|
||||
expect(body['id_token'], 'id');
|
||||
expect(body['refresh_token'], 'refresh');
|
||||
expect(body['expires_at'], '2026-01-01T00:00:00.000Z');
|
||||
expect(body['email'], 'seeded@example.com');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'serves credentials with a null email when firebase.json is absent',
|
||||
() async {
|
||||
final credentialsDir = Directory(p.join(root.path, 'todo-config-2'))
|
||||
..createSync(recursive: true);
|
||||
final credentialsPath = p.join(
|
||||
credentialsDir.path,
|
||||
'firebase_auth.json',
|
||||
);
|
||||
File(credentialsPath).writeAsStringSync(
|
||||
jsonEncode({
|
||||
'id_token': 'id',
|
||||
'refresh_token': 'refresh',
|
||||
'expires_at': '2026-01-01T00:00:00.000Z',
|
||||
}),
|
||||
);
|
||||
final enabled = WrapperServer(
|
||||
webRoot: p.join(root.path, 'web'),
|
||||
backlogPath: p.join(root.path, 'todo', 'BACKLOG.md'),
|
||||
logPath: p.join(root.path, 'state', 'todo_notes.json'),
|
||||
serveSyncAccount: true,
|
||||
syncConfigDir: p.join(root.path, 'crdt-sync-absent'),
|
||||
todoCredentialsPath: credentialsPath,
|
||||
);
|
||||
await enabled.start(0);
|
||||
addTearDown(enabled.stop);
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('http://localhost:${enabled.port}$kSyncCredentialsPath'),
|
||||
);
|
||||
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
|
||||
expect(response.statusCode, HttpStatus.ok);
|
||||
expect(body['email'], isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('is 404 when the credentials file is absent', () async {
|
||||
final origin = await enabledOrigin({});
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||
);
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test('is 404 when the credentials file is not valid JSON', () async {
|
||||
final origin = await enabledOrigin({}, credentialsJson: 'not json');
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||
);
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
});
|
||||
|
||||
test(
|
||||
'is 404 when the credentials file is missing required fields',
|
||||
() async {
|
||||
final origin = await enabledOrigin(
|
||||
{},
|
||||
credentialsJson: jsonEncode({'id_token': 'id'}),
|
||||
);
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('$origin$kSyncCredentialsPath'),
|
||||
);
|
||||
|
||||
expect(response.statusCode, HttpStatus.notFound);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user