diff --git a/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart b/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart index bebcfb23e24f..90cd4f2ae158 100644 --- a/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart +++ b/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart @@ -58,6 +58,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { try { response = await callable.call(parametersJS); } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } @@ -100,6 +101,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { yield value; } } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } } @@ -116,6 +118,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { return web.AbortSignal.any(jsSignals); } } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } } diff --git a/packages/cloud_functions/cloud_functions_web/lib/utils.dart b/packages/cloud_functions/cloud_functions_web/lib/utils.dart index a3538e1589e3..18971c5c9a4e 100644 --- a/packages/cloud_functions/cloud_functions_web/lib/utils.dart +++ b/packages/cloud_functions/cloud_functions_web/lib/utils.dart @@ -8,16 +8,37 @@ import 'dart:js_interop_unsafe'; import 'package:cloud_functions_platform_interface/cloud_functions_platform_interface.dart'; +/// Whether [error] is a JS error from the Functions SDK, that is a JS object +/// with a string `code`. +/// +/// Dart errors and other JS errors return `false` and should be rethrown +/// as they are. +bool isFirebaseFunctionsError(Object? error) { + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. + // ignore: invalid_runtime_check_with_js_interop_types + return error is JSObject && error.getProperty('code'.toJS).isA(); +} + +/// Returns the string value of [property] on [object], or `null`. +String? _stringProperty(JSObject object, String property) { + final value = object.getProperty(property.toJS); + if (value != null && value.isA()) { + return (value as JSString).toDart; + } + return null; +} + /// Given a web error, a [FirebaseFunctionsException] is returned. FirebaseFunctionsException convertFirebaseFunctionsException( JSObject exception, [ StackTrace? stackTrace, ]) { - String originalCode = - (exception.getProperty('code'.toJS)! as JSString).toDart; + String originalCode = _stringProperty(exception, 'code') ?? 'unknown'; String code = originalCode.replaceFirst('functions/', ''); - String message = (exception.getProperty('message'.toJS)! as JSString).toDart - .replaceFirst('($originalCode)', ''); + String message = (_stringProperty(exception, 'message') ?? '').replaceFirst( + '($originalCode)', + '', + ); return FirebaseFunctionsException( code: code, diff --git a/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart new file mode 100644 index 000000000000..e6fb5331307b --- /dev/null +++ b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart @@ -0,0 +1,168 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@TestOn('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:cloud_functions_platform_interface/cloud_functions_platform_interface.dart'; +import 'package:cloud_functions_web/https_callable_web.dart'; +import 'package:cloud_functions_web/interop/functions.dart' + as functions_interop; +import 'package:cloud_functions_web/interop/functions_interop.dart' + show FunctionsJsImpl; +import 'package:flutter_test/flutter_test.dart'; + +class _FakeFunctions extends FirebaseFunctionsPlatform { + _FakeFunctions() : super(null, 'us-central1'); +} + +/// A JS error shaped like the `FunctionsError` the JS SDK rejects with. +JSObject _functionsError() { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor('not allowed'.toJS); + error['name'] = 'FirebaseError'.toJS; + error['code'] = 'functions/permission-denied'.toJS; + error['details'] = {'reason': 'quota'}.jsify(); + return error; +} + +JSPromise _rejectWith(JSAny error) => globalContext + .getProperty('Promise'.toJS) + .callMethod('reject'.toJS, error); + +/// Matches the exact JS value [expected], not a wrapper around it. +Matcher _isJsValue(JSAny expected) => predicate( + // ignore: invalid_runtime_check_with_js_interop_types + (e) => e is JSObject && e.strictEquals(expected).toDart, + 'is the original JS error', +); + +void main() { + /// Points the JS SDK's `httpsCallable()` at [callable]. + HttpsCallableWeb callableReturning( + JSFunction callable, { + HttpsCallableOptions? options, + }) { + final sdk = JSObject(); + // `stream()` calls `httpsCallable()` without options, `call()` with them. + sdk['httpsCallable'] = + ((JSAny? functions, JSAny? name, [JSAny? options]) => callable).toJS; + globalContext['firebase_functions'] = sdk; + + return HttpsCallableWeb( + _FakeFunctions(), + functions_interop.Functions.getInstance(JSObject() as FunctionsJsImpl), + null, + 'fn', + options ?? HttpsCallableOptions(), + null, + ); + } + + /// A callable whose `call()` and `stream()` both run [onCall]. + JSFunction callable(JSAny? Function() onCall) { + final fn = ((JSAny? data) => onCall()).toJS; + fn['stream'] = ((JSAny? data, JSAny? options) => onCall()).toJS; + return fn; + } + + group('call()', () { + test('maps a FunctionsError to FirebaseFunctionsException', () async { + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + ); + + await expectLater( + web.call(), + throwsA( + isA() + .having((e) => e.code, 'code', 'permission-denied') + .having((e) => e.message, 'message', 'not allowed') + .having((e) => e.details, 'details', {'reason': 'quota'}), + ), + ); + }); + + test('rethrows a JS rejection that has no code or message', () async { + final error = JSObject(); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.call(), throwsA(_isJsValue(error))); + }); + + test('rethrows a plain JS Error that has no code', () async { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor('network down'.toJS); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.call(), throwsA(_isJsValue(error))); + }); + + test('rethrows a Dart error unchanged', () async { + final web = callableReturning(callable(() => throw StateError('boom'))); + + await expectLater( + web.call(), + throwsA(isA().having((e) => e.message, 'message', 'boom')), + ); + }); + }); + + group('stream()', () { + test('maps a FunctionsError to FirebaseFunctionsException', () async { + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + ); + + await expectLater( + web.stream(null), + emitsError( + isA().having( + (e) => e.code, + 'code', + 'permission-denied', + ), + ), + ); + }); + + test('rethrows a JS rejection that has no code or message', () async { + final error = JSObject(); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.stream(null), emitsError(_isJsValue(error))); + }); + + test('rethrows a Dart error unchanged', () async { + final web = callableReturning(callable(() => throw StateError('boom'))); + + await expectLater(web.stream(null), emitsError(isA())); + }); + + test('rethrows the error from an invalid abort signal', () async { + // `AbortSignal.timeout()` rejects a negative delay with a JS TypeError. + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + options: HttpsCallableOptions( + webAbortSignal: TimeLimit(const Duration(milliseconds: -1)), + ), + ); + + await expectLater( + web.stream(null), + emitsError( + predicate( + (e) => e.toString().contains('AbortSignal'), + 'is the original AbortSignal error', + ), + ), + ); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart b/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart index 66fc4d6513a6..916feba0ced2 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart @@ -5,6 +5,7 @@ import 'dart:async'; import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; import 'package:firebase_auth_web/src/firebase_auth_web_multi_factor.dart'; @@ -527,16 +528,18 @@ class FirebaseAuthWeb extends FirebaseAuthPlatform { ); } } catch (e) { - // Cannot be done with 3.2 constraints + // `is AuthError` would match any JS object, so check for one directly. + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. // ignore: invalid_runtime_check_with_js_interop_types - if (e is auth_interop.AuthError) { - final String code = e.code.toDart; - // this catches Firebase Error from web that occurs after hot reloading & hot restarting - if (code != 'auth/emulator-config-failed') { - throw getFirebaseAuthException(e); - } - } else { - rethrow; + if (e is! JSObject) rethrow; + // Not every JS error has a string `code`, so compare it in JS. + final isEmulatorConfigFailed = e + .getProperty('code'.toJS) + .strictEquals('auth/emulator-config-failed'.toJS) + .toDart; + // this catches Firebase Error from web that occurs after hot reloading & hot restarting + if (!isEmulatorConfigFailed) { + throw getFirebaseAuthException(e); } } } @@ -589,7 +592,10 @@ class FirebaseAuthWeb extends FirebaseAuthPlatform { ); codeSent(verificationId, null); - } catch (e) { + } catch (e, stackTrace) { + // A Dart error, for example from `codeSent`, is not a failed + // verification: rethrow it. + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); verificationFailed(getFirebaseAuthException(e)); } } diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart index 80e380c3d47c..7089924af969 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart @@ -147,7 +147,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform { Future verify() { try { return _delegate.verify(); - } catch (e) { + } catch (e, stackTrace) { + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); throw getFirebaseAuthException(e); } } @@ -156,7 +157,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform { Future render() async { try { return await _delegate.render(); - } catch (e) { + } catch (e, stackTrace) { + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); throw getFirebaseAuthException(e); } } diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart index 24db8f844fbd..2e84389ba8c6 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart @@ -28,26 +28,40 @@ bool _hasFirebaseAuthErrorCodeAndMessage(JSError e) { } } +/// Whether [error] is a JS object, as opposed to a Dart error. +/// +/// `@staticInterop` types such as [JSError] match any JS object at runtime, so +/// this is the check to make before casting a caught error to one. Callers +/// should rethrow anything else unchanged. +bool isJSObject(Object? error) { + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. + // ignore: invalid_runtime_check_with_js_interop_types + return error is JSObject; +} + R guardAuthExceptions(R Function() cb, {auth_interop.Auth? auth}) { try { final value = cb(); if (value is Future) { - return value.catchError((err, stack) { - final exception = getFirebaseAuthException(err, auth); - return Error.throwWithStackTrace(exception, stack); - }) + return value.catchError( + (Object err, StackTrace stack) => Error.throwWithStackTrace( + getFirebaseAuthException(err, auth), + stack, + ), + // Dart errors are rethrown as they are, with their stack trace. + test: isJSObject, + ) as R; } return value; } catch (e, stackTrace) { - final exception = e as JSError; - if (!_hasFirebaseAuthErrorCodeAndMessage(e)) { + if (!isJSObject(e) || !_hasFirebaseAuthErrorCodeAndMessage(e as JSError)) { // Not a firebase auth exception, rethrow & make sure to preserve the stacktrace rethrow; } - final error = getFirebaseAuthException(exception, auth); + final error = getFirebaseAuthException(e, auth); Error.throwWithStackTrace(error, stackTrace); } @@ -61,6 +75,13 @@ FirebaseAuthException getFirebaseAuthException( Object objectException, [ auth_interop.Auth? auth, ]) { + if (!isJSObject(objectException)) { + return FirebaseAuthException( + code: 'unknown', + message: 'An unknown error occurred: $objectException', + ); + } + final exception = objectException as JSError; final authJsCredential = auth_interop.OAuthProviderJsImpl.credentialFromError( exception, diff --git a/packages/firebase_auth/firebase_auth_web/pubspec.yaml b/packages/firebase_auth/firebase_auth_web/pubspec.yaml index e18156e790a5..48ecd0a8bd5c 100644 --- a/packages/firebase_auth/firebase_auth_web/pubspec.yaml +++ b/packages/firebase_auth/firebase_auth_web/pubspec.yaml @@ -22,6 +22,7 @@ dependencies: web: ^1.0.0 dev_dependencies: + firebase_core_platform_interface: ^8.1.1 flutter_test: sdk: flutter diff --git a/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart b/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart new file mode 100644 index 000000000000..8cd2fef678f1 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart @@ -0,0 +1,86 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; + +/// Makes `Firebase.app()` return an app without `Firebase.initializeApp()`, +/// so `FirebaseAuthWeb.instance` can be used in tests. +class FakeFirebase extends FirebasePlatform { + @override + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + return FirebaseAppPlatform( + name, + const FirebaseOptions( + apiKey: 'api-key', + appId: 'app-id', + messagingSenderId: 'sender-id', + projectId: 'project-id', + ), + ); + } +} + +/// A JS `Error`. With a [code], it is shaped like the `FirebaseError` the +/// Auth JS SDK throws. +JSObject jsError(String message, {String? code}) { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor(message.toJS); + if (code != null) { + error['name'] = 'FirebaseError'.toJS; + error['code'] = code.toJS; + } + return error; +} + +/// A JS promise that rejects with [error]. +JSPromise rejectWith(JSAny error) => globalContext + .getProperty('Promise'.toJS) + .callMethod('reject'.toJS, error); + +/// A JS promise that resolves with [value]. +JSPromise resolveWith(JSAny? value) => globalContext + .getProperty('Promise'.toJS) + .callMethod('resolve'.toJS, value); + +/// A JS function that returns [instance] when called with `new`. +JSFunction jsConstructor(JSObject instance) => globalContext + .getProperty('Function'.toJS) + .callAsConstructor( + 'instance'.toJS, + 'return function () { return instance; };'.toJS, + ) + // `callMethod` drops arguments after the first `null`, so pass a `this`. + .callMethod('call'.toJS, globalContext, instance); + +/// Installs the parts of the `firebase_core` and `firebase_auth` JS SDKs that +/// `FirebaseAuthWeb.delegate` needs, and returns the `firebase_auth` object so +/// a test can add the functions it calls. +JSObject stubFirebaseAuthJsSdk() { + final core = JSObject(); + core['getApp'] = (([JSAny? name]) => JSObject()).toJS; + globalContext['firebase_core'] = core; + + // getFirebaseAuthException always calls OAuthProvider.credentialFromError. + final oauthProvider = JSObject(); + oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; + + final auth = JSObject(); + for (final name in [ + 'indexedDBLocalPersistence', + 'browserLocalPersistence', + 'browserSessionPersistence', + 'debugErrorMap', + 'browserPopupRedirectResolver', + ]) { + auth[name] = JSObject(); + } + auth['OAuthProvider'] = oauthProvider; + auth['initializeAuth'] = ((JSAny? app, JSAny? options) => JSObject()).toJS; + globalContext['firebase_auth'] = auth; + return auth; +} diff --git a/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart b/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart index c62f8fa1fac3..52a8bbd82edc 100644 --- a/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart +++ b/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart @@ -58,4 +58,11 @@ void main() { expect(exception.code, 'invalid-credential'); expect(exception.email, 'user@example.com'); }); + + test('returns an unknown error for a Dart error instead of throwing', () { + final exception = getFirebaseAuthException(StateError('boom')); + + expect(exception.code, 'unknown'); + expect(exception.message, contains('boom')); + }); } diff --git a/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart new file mode 100644 index 000000000000..e76ecd92884b --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart @@ -0,0 +1,116 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@TestOn('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; +import 'package:firebase_auth_web/src/utils/web_utils.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// A JS error shaped like the `FirebaseError` the Auth JS SDK throws. +JSObject _firebaseAuthError() { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor( + 'Firebase: Error (auth/user-disabled).'.toJS, + ); + error['name'] = 'FirebaseError'.toJS; + error['code'] = 'auth/user-disabled'.toJS; + return error; +} + +/// Matches the exact JS value [expected], not a wrapper around it. +Matcher _isJsValue(JSAny expected) => predicate( + // ignore: invalid_runtime_check_with_js_interop_types + (e) => e is JSObject && e.strictEquals(expected).toDart, + 'is the original JS error', +); + +void main() { + setUp(() { + // getFirebaseAuthException always calls OAuthProvider.credentialFromError. + // Stub it so this test does not need the full Auth JS SDK. + final oauthProvider = JSObject(); + oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; + final firebaseAuth = JSObject(); + firebaseAuth['OAuthProvider'] = oauthProvider; + globalContext['firebase_auth'] = firebaseAuth; + }); + + group('guardAuthExceptions with a sync callback', () { + test('maps a Firebase Auth error to FirebaseAuthException', () { + expect( + () => guardAuthExceptions(() => throw _firebaseAuthError()), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'user-disabled', + ), + ), + ); + }); + + test('rethrows a JS error without code or message unchanged', () { + final error = JSObject(); + + expect( + () => guardAuthExceptions(() => throw error), + throwsA(_isJsValue(error)), + ); + }); + + test('rethrows a Dart error unchanged', () { + expect( + () => guardAuthExceptions(() => throw StateError('boom')), + throwsA(isA().having((e) => e.message, 'message', 'boom')), + ); + }); + }); + + group('guardAuthExceptions with a Future callback', () { + test('maps a Firebase Auth error to FirebaseAuthException', () async { + await expectLater( + guardAuthExceptions(() => Future.error(_firebaseAuthError())), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'user-disabled', + ), + ), + ); + }); + + test('maps a JS error without code or message to unknown', () async { + await expectLater( + guardAuthExceptions(() => Future.error(JSObject())), + throwsA( + isA().having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + + test('rethrows a Dart error with its stack trace', () async { + final error = StateError('boom'); + final stackTrace = StackTrace.current; + + Object? caught; + StackTrace? caughtStackTrace; + try { + await guardAuthExceptions(() => Future.error(error, stackTrace)); + } catch (e, s) { + caught = e; + caughtStackTrace = s; + } + + expect(caught, same(error)); + expect(caughtStackTrace.toString(), stackTrace.toString()); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart b/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart new file mode 100644 index 000000000000..5ab6cff5a5b6 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart @@ -0,0 +1,152 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@TestOn('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; +import 'package:firebase_auth_web/firebase_auth_web.dart'; +import 'package:firebase_auth_web/src/firebase_auth_web_recaptcha_verifier_factory.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'fake_auth_js_sdk.dart'; + +void main() { + setUpAll(() { + FirebasePlatform.instance = FakeFirebase(); + }); + + /// Installs the JS SDK, where `new RecaptchaVerifier()` returns + /// [recaptchaVerifier] and `PhoneAuthProvider.verifyPhoneNumber()` runs + /// [verifyPhoneNumber]. + void stubSdk({ + JSObject? recaptchaVerifier, + JSPromise Function()? verifyPhoneNumber, + }) { + final phoneAuthProvider = JSObject(); + if (verifyPhoneNumber != null) { + phoneAuthProvider['verifyPhoneNumber'] = + ((JSAny? options, JSAny? verifier) => verifyPhoneNumber()).toJS; + } + + final auth = stubFirebaseAuthJsSdk(); + auth['PhoneAuthProvider'] = jsConstructor(phoneAuthProvider); + auth['RecaptchaVerifier'] = jsConstructor(recaptchaVerifier ?? JSObject()); + } + + group('verifyPhoneNumber', () { + final failures = []; + + setUp(failures.clear); + + Future verifyPhoneNumber({ + PhoneCodeSent? codeSent, + MultiFactorSession? multiFactorSession, + }) { + return FirebaseAuthWeb.instance.verifyPhoneNumber( + phoneNumber: '+15555550100', + multiFactorSession: multiFactorSession, + verificationCompleted: (_) {}, + verificationFailed: failures.add, + codeSent: codeSent ?? (_, __) {}, + codeAutoRetrievalTimeout: (_) {}, + ); + } + + test('reports a Firebase Auth error to verificationFailed', () async { + stubSdk( + verifyPhoneNumber: () => rejectWith( + jsError( + 'Firebase: Error (auth/invalid-phone-number).', + code: 'auth/invalid-phone-number', + ), + ), + ); + + await verifyPhoneNumber(); + + expect(failures.single.code, 'invalid-phone-number'); + }); + + test('rethrows a Dart error thrown by codeSent', () async { + stubSdk(verifyPhoneNumber: () => resolveWith('verification-id'.toJS)); + + await expectLater( + verifyPhoneNumber(codeSent: (_, __) => throw StateError('boom')), + throwsA(isA()), + ); + expect(failures, isEmpty); + }); + + test( + 'rethrows the cast error for a multiFactorSession from another platform', + () async { + stubSdk(); + + await expectLater( + verifyPhoneNumber(multiFactorSession: MultiFactorSession('id')), + throwsA(isA()), + ); + expect(failures, isEmpty); + }, + ); + }); + + group('RecaptchaVerifierFactoryWeb', () { + RecaptchaVerifierFactoryWeb verifierWith(JSObject recaptchaVerifier) { + stubSdk(recaptchaVerifier: recaptchaVerifier); + return RecaptchaVerifierFactoryWeb(auth: FirebaseAuthWeb.instance); + } + + test( + 'render maps a Firebase Auth error to FirebaseAuthException', + () async { + final recaptchaVerifier = JSObject(); + recaptchaVerifier['render'] = (() => rejectWith( + jsError( + 'Firebase: Error (auth/captcha-check-failed).', + code: 'auth/captcha-check-failed', + ), + )).toJS; + + await expectLater( + verifierWith(recaptchaVerifier).render(), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'captcha-check-failed', + ), + ), + ); + }, + ); + + test('render rethrows a Dart error unchanged', () async { + JSPromise render() => throw StateError('boom'); + final recaptchaVerifier = JSObject(); + recaptchaVerifier['render'] = render.toJS; + + await expectLater( + verifierWith(recaptchaVerifier).render(), + throwsA(isA()), + ); + }); + + test('verify rethrows a Dart error unchanged', () { + JSPromise verify() => throw StateError('boom'); + final recaptchaVerifier = JSObject(); + recaptchaVerifier['verify'] = verify.toJS; + + expect( + () => verifierWith(recaptchaVerifier).verify(), + throwsA(isA()), + ); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart new file mode 100644 index 000000000000..447438d47543 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart @@ -0,0 +1,79 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@TestOn('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; +import 'package:firebase_auth_web/firebase_auth_web.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'fake_auth_js_sdk.dart'; + +void main() { + setUpAll(() { + FirebasePlatform.instance = FakeFirebase(); + }); + + /// Stubs the JS SDK so that `connectAuthEmulator()` throws [error]. + void connectAuthEmulatorThrows(Object error) { + void connectAuthEmulator(JSAny? auth, JSAny? origin) => throw error; + stubFirebaseAuthJsSdk()['connectAuthEmulator'] = connectAuthEmulator.toJS; + } + + test('ignores auth/emulator-config-failed after a hot restart', () async { + connectAuthEmulatorThrows( + jsError( + 'Firebase: Error (auth/emulator-config-failed).', + code: 'auth/emulator-config-failed', + ), + ); + + await FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099); + }); + + test('maps a Firebase Auth error to FirebaseAuthException', () async { + connectAuthEmulatorThrows( + jsError( + 'Firebase: Error (auth/invalid-emulator-scheme).', + code: 'auth/invalid-emulator-scheme', + ), + ); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'invalid-emulator-scheme', + ), + ), + ); + }); + + test('maps a JS error without code to an unknown error', () async { + connectAuthEmulatorThrows(jsError('storage is disabled')); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA( + isA().having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + + test('rethrows a Dart error unchanged', () async { + connectAuthEmulatorThrows(StateError('boom')); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA(isA()), + ); + }); +}