Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@ Without it, apps are named after the `name` in your `pubspec.yaml`, so white lab

This only affects apps FlutterFire CLI creates. Android, iOS and macOS apps that already exist on the project are matched by their package name or bundle ID and keep the name they have. Web and Windows have neither, so they are matched on display name instead. If no web app has a matching name, the first web app on the project is reused, so a custom name does not guarantee a new web app; Windows creates a new app instead. Pass `--web-app-id` / `--windows-app-id` to pick one explicitly.

### Filtering Android OAuth 2.0 Client IDs by SHA-1 (`--android-sha1`)

If your Firebase project has multiple Android OAuth 2.0 Client IDs (e.g., for different SHA-1 certificate fingerprints such as debug, release, or Play App Signing), you can filter which client ID is retrieved and populated using the `--android-sha1` flag.

It supports exact matching as well as wildcard search (`*`, `?`):

```bash
flutterfire configure --yes --project=<FIREBASE_PROJECT_ID> --android-sha1="8120d965673*"
```

### Firebase Cloud Messaging on the web

`firebase_messaging` needs a service worker at `web/firebase-messaging-sw.js` to receive messages while your web app is in the background, and a service worker cannot read `firebase_options.dart`. When your app depends on `firebase_messaging` and you configure the web platform, FlutterFire CLI writes that file for you with the Firebase configuration of your web app.
Expand Down
4 changes: 4 additions & 0 deletions packages/flutterfire_cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
- **FEAT**: add `--display-name` flag to `flutterfire configure` ([#457](https://github.com/invertase/flutterfire_cli/issues/457)). ([ba609da0](https://github.com/invertase/flutterfire_cli/commit/ba609da08f46d2da3e0944e131f0a1ea9e478b4f))
- **DOCS**: fix outdated and broken examples in the READMEs ([#470](https://github.com/invertase/flutterfire_cli/issues/470)). ([54cde6cc](https://github.com/invertase/flutterfire_cli/commit/54cde6ccc6b6c346c7869a502170d14677aca4e2))

## 1.4.2

- **FEAT**: add `--android-sha1` flag to filter Android OAuth 2.0 Client IDs and patch `GoogleService-Info.plist` with wildcard SHA-1 search support.

## 1.4.1

- **FIX**: stop generating reCAPTCHA site key in Firebase options ([#454](https://github.com/invertase/flutterfire_cli/issues/454)). ([0685d1cb](https://github.com/invertase/flutterfire_cli/commit/0685d1cb34ede011cb8a8f5c0f2b1271acc90ecc))
Expand Down
11 changes: 11 additions & 0 deletions packages/flutterfire_cli/lib/src/commands/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ class ConfigCommand extends FlutterFireCommand {
'If no package name is provided then an attempt will be made to '
'automatically detect it from your "android" folder (if it exists).',
);
argParser.addOption(
'android-sha1',
valueHelp: 'sha1',
help: 'Filter Android OAuth 2.0 Client IDs by SHA-1 fingerprint '
'(supports exact match or wildcard search, e.g. "*ABCD*").',
);
argParser.addOption(
kWebAppIdFlag,
valueHelp: 'appId',
Expand Down Expand Up @@ -297,6 +303,10 @@ class ConfigCommand extends FlutterFireCommand {
return argResults!['android-out'] as String?;
}

String? get androidSha1 {
return argResults!['android-sha1'] as String?;
}

String? get androidApplicationId {
final value = argResults!['android-package-name'] as String?;
final deprecatedValue = argResults!['android-app-id'] as String?;
Expand Down Expand Up @@ -687,6 +697,7 @@ class ConfigCommand extends FlutterFireCommand {
web: selectedPlatforms[kWeb]!,
windows: selectedPlatforms[kWindows]!,
linux: selectedPlatforms[kLinux] != null && selectedPlatforms[kLinux]!,
androidSha1: androidSha1,
);

// 4. Writes for all selected platforms
Expand Down
14 changes: 14 additions & 0 deletions packages/flutterfire_cli/lib/src/commands/reconfigure.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ class Reconfigure extends FlutterFireCommand {
help:
'Set the access token for making Firebase API requests. Required for CI environment.',
);
argParser.addOption(
'android-sha1',
valueHelp: 'sha1',
help: 'Filter Android OAuth 2.0 Client IDs by SHA-1 fingerprint '
'(supports exact match or wildcard search, e.g. "*ABCD*").',
);
}

@override
Expand All @@ -87,6 +93,13 @@ class Reconfigure extends FlutterFireCommand {
return _accessToken;
}

String? get androidSha1 {
if (argResults != null) {
return argResults!['android-sha1'] as String?;
}
return null;
}

set accessToken(String? value) {
_accessToken = value;
}
Expand Down Expand Up @@ -294,6 +307,7 @@ class Reconfigure extends FlutterFireCommand {
appSdkConfig,
appId,
projectId,
androidSha1: androidSha1,
);
break;
case kIos:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import 'dart:convert';
import 'package:deep_pick/deep_pick.dart';

import '../common/global.dart';
import '../common/strings.dart';
import '../common/utils.dart';
import '../firebase.dart' as firebase;
Expand All @@ -26,6 +27,185 @@ import '../flutter_app.dart';
import 'firebase_options.dart';

extension FirebaseAndroidOptions on FirebaseOptions {
static bool matchesSha1(String? certificateHash, String? query) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Checking certificate_hash: "$certificateHash" against query: "$query"');
}
if (certificateHash == null || query == null || query.isEmpty) return true;

String normalize(String s, {bool isQuery = false}) {
var res = s.replaceAll(RegExp(r'[:\-]'), '');
if (isQuery) {
res = res.replaceAll(RegExp('^=+'), '');
}
return res.toLowerCase();
}

final normalizedHash = normalize(certificateHash);
final normalizedQuery = normalize(query, isQuery: true);

if (normalizedQuery.contains('*') || normalizedQuery.contains('?')) {
final pattern = '^${normalizedQuery
.replaceAll('.', r'\.')
.replaceAll('*', '.*')
.replaceAll('?', '.')
}\$';
try {
final matches = RegExp(pattern).hasMatch(normalizedHash);
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Wildcard match result for "$certificateHash" with pattern "$pattern": $matches');
}
return matches;
} catch (e) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Wildcard regex error: $e');
}
return false;
}
}

final matches = normalizedHash == normalizedQuery;
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Exact match result for "$certificateHash" with query "$query": $matches');
}
return matches;
}

static Map<Object?, Object?>? getAndroidClientId(
Map<Object?, Object?> clientMap, {
String? androidSha1,
}) {
final oauthClients =
pick(clientMap, 'oauth_client').asListOrNull<Map>((pick) {
return pick.asMapOrEmpty<Object?, Object?>();
});
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidClientId: found ${oauthClients?.length ?? 0} oauth_clients for client. androidSha1 filter: $androidSha1');
}
if (oauthClients == null || oauthClients.isEmpty) return null;

// Filter for Android client type (client_type == 1)
final androidOauthClients = oauthClients.where((client) {
final clientType = client['client_type'];
return clientType == 1 || clientType == '1';
}).toList();

if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidOAuthClient: found ${androidOauthClients.length} Android oauth clients (client_type == 1)');
}

if (androidOauthClients.isEmpty) return null;

if (androidSha1 != null && androidSha1.isNotEmpty) {
for (final client in androidOauthClients) {
final androidInfo = client['android_info'];
final certificateHash = androidInfo is Map
? androidInfo['certificate_hash'] as String?
: null;
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Examining Android OAuth client: clientId=${client['client_id']}, certificateHash=$certificateHash');
}
if (matchesSha1(certificateHash, androidSha1)) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Matched Android OAuth client: $client');
}
return client;
}
}
}

// Fallback to the first Android OAuth client if no SHA-1 filter or no match found
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Fallback to first Android OAuth client: ${androidOauthClients.first}');
}
return androidOauthClients.first;
}

static Future<Map<Object?, Object?>?> getAndroidClientIdForProject({
required String projectId,
required String? account,
required String? token,
required String? serviceAccount,
required String androidSha1,
}) async {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidClientIdForProject starting with projectId=$projectId, androidSha1=$androidSha1');
}
try {
final androidApps = await firebase.getApps(
project: projectId,
account: account,
platform: kAndroid,
token: token,
serviceAccount: serviceAccount,
);
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Found ${androidApps.length} android apps in project.');
}
for (final app in androidApps) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Fetching SDK config for appId=${app.appId}, packageName=${app.packageNameOrBundleIdentifier}');
}
final appSdkConfig = await firebase.getAppSdkConfig(
appId: app.appId,
platform: kAndroid,
account: account,
token: token,
serviceAccount: serviceAccount,
);
final appSdkConfigMap = const JsonDecoder()
.convert(appSdkConfig.fileContents) as Map<String, dynamic>;
final clients =
pick(appSdkConfigMap, 'client').asListOrThrow<Map>((pick) {
return pick.asMapOrEmpty<Object?, Object?>();
});
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] Found ${clients.length} clients in appSdkConfigMap.');
}

for (final client in clients) {
final oauthClient = getAndroidClientId(client, androidSha1: androidSha1);
if (oauthClient != null) {
final androidInfo = oauthClient['android_info'];
final certificateHash = androidInfo is Map
? androidInfo['certificate_hash'] as String?
: null;
if (matchesSha1(certificateHash, androidSha1)) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidClientIdForProject matched oauthClient: $oauthClient');
}
return oauthClient;
}
}
}
}
} catch (e, st) {
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidClientIdForProject error: $e\n$st');
}
}
if (debugMode) {
// ignore: avoid_print
print('[FlutterFire CLI] getAndroidClientIdForProject found no match.');
}
return null;
}

static String projectIdFromFileContents(String fileContents) {
final appSdkConfigMap =
const JsonDecoder().convert(fileContents) as Map<String, dynamic>;
Expand All @@ -41,6 +221,7 @@ extension FirebaseAndroidOptions on FirebaseOptions {
required String displayName,
required String? token,
required String? serviceAccount,
String? androidSha1,
}) async {
var selectedAndroidApplicationId =
androidApplicationId ?? flutterApp.androidApplicationId;
Expand Down Expand Up @@ -76,36 +257,76 @@ extension FirebaseAndroidOptions on FirebaseOptions {
appSdkConfig,
firebaseApp.appId,
firebaseProjectId,
androidSha1: androidSha1,
);
}

static FirebaseOptions convertConfigToOptions(
FirebaseAppSdkConfig appSdkConfig,
String appId,
String firebaseProjectId,
) {
String firebaseProjectId, {
String? androidSha1,
}) {
final appSdkConfigMap = const JsonDecoder()
.convert(appSdkConfig.fileContents) as Map<String, dynamic>;
final clientMap =
pick(appSdkConfigMap, 'client').asListOrThrow<Map>((pick) {
return pick.asMapOrEmpty<String, dynamic>();
}).firstWhere(

final clients = pick(appSdkConfigMap, 'client').asListOrThrow<Map>((pick) {
return pick.asMapOrEmpty<Object?, Object?>();
});

Map<Object?, Object?>? clientMap;

if (androidSha1 != null && androidSha1.isNotEmpty) {
for (final client in clients) {
final oauthClients =
pick(client, 'oauth_client').asListOrNull<Map>((pick) {
return pick.asMapOrEmpty<Object?, Object?>();
});
if (oauthClients != null) {
for (final oauthClient in oauthClients) {
final clientType = oauthClient['client_type'];
if (clientType == 1 || clientType == '1') {
final androidInfo = oauthClient['android_info'];
final certificateHash = androidInfo is Map
? androidInfo['certificate_hash'] as String?
: null;
if (matchesSha1(certificateHash, androidSha1)) {
clientMap = client;
break;
}
}
}
}
if (clientMap != null) break;
}
}

clientMap ??= clients.firstWhere(
(client) =>
pick(client, 'client_info', 'mobilesdk_app_id').asStringOrThrow() ==
appId,
orElse: () => clients.first,
);

final resolvedAppId =
pick(clientMap, 'client_info', 'mobilesdk_app_id').asStringOrNull() ??
appId;

final androidOAuthClient = getAndroidClientId(clientMap, androidSha1: androidSha1);

return FirebaseOptions(
optionsSourceContent: appSdkConfig.fileContents,
optionsSourceFileName: appSdkConfig.fileName,
apiKey: pick(clientMap, 'api_key', 0, 'current_key').asStringOrThrow(),
appId: appId,
appId: resolvedAppId,
projectId: firebaseProjectId,
messagingSenderId: pick(appSdkConfigMap, 'project_info', 'project_number')
.asStringOrThrow(),
databaseURL: pick(appSdkConfigMap, 'project_info', 'firebase_url')
.asStringOrNull(),
storageBucket: pick(appSdkConfigMap, 'project_info', 'storage_bucket')
.asStringOrNull(),
androidClientId: androidOAuthClient?['client_id'] as String?,
);
}
}
Loading
Loading