Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -100,6 +101,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform {
yield value;
}
} catch (e, s) {
if (!isFirebaseFunctionsError(e)) rethrow;
throw convertFirebaseFunctionsException(e as JSObject, s);
}
}
Expand All @@ -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);
}
}
Expand Down
29 changes: 25 additions & 4 deletions packages/cloud_functions/cloud_functions_web/lib/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<JSString>();
}

/// 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<JSString>()) {
return (value as JSString).toDart;
}
return null;
}
Comment on lines +23 to +29

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low

According to the repository style guide (Rule 23), the ! operator is prohibited. We should avoid using ! and instead use flow analysis or direct casting.

String? _stringProperty(JSObject object, String property) {
  final value = object.getProperty(property.toJS);
  if (value.isA<JSString>()) {
    return (value as JSString).toDart;
  }
  return null;
}
References
  1. Null Safety: NO ! operator. Use ? and flow analysis (e.g. if (x != null)). (link)


/// 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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<JSFunction>('Error'.toJS)
.callAsConstructor<JSObject>('not allowed'.toJS);
error['name'] = 'FirebaseError'.toJS;
error['code'] = 'functions/permission-denied'.toJS;
error['details'] = {'reason': 'quota'}.jsify();
return error;
Comment on lines +24 to +31

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low

According to the repository style guide (Rule 23), the ! operator is prohibited. We can avoid it by casting directly using as JSFunction.

JSObject _functionsError() {
  final error = (globalContext['Error'] as JSFunction)
      .callAsConstructor<JSObject>('not allowed'.toJS);
  error['name'] = 'FirebaseError'.toJS;
  error['code'] = 'functions/permission-denied'.toJS;
  error['details'] = {'reason': 'quota'}.jsify();
  return error;
References
  1. Null Safety: NO ! operator. Use ? and flow analysis (e.g. if (x != null)). (link)

}

JSPromise _rejectWith(JSAny error) => globalContext
.getProperty<JSObject>('Promise'.toJS)
.callMethod<JSPromise>('reject'.toJS, error);

/// Matches the exact JS value [expected], not a wrapper around it.
Matcher _isJsValue(JSAny expected) => predicate<Object>(
// 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<FirebaseFunctionsException>()
.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<JSFunction>('Error'.toJS)
.callAsConstructor<JSObject>('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<StateError>().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<FirebaseFunctionsException>().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<StateError>()));
});

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<Object>(
(e) => e.toString().contains('AbortSignal'),
'is the original AbortSignal error',
),
),
);
});
});
}
26 changes: 16 additions & 10 deletions packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
}
}
Expand Down Expand Up @@ -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));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform {
Future<String> verify() {
try {
return _delegate.verify();
} catch (e) {
} catch (e, stackTrace) {
if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace);
throw getFirebaseAuthException(e);
}
}
Expand All @@ -156,7 +157,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform {
Future<int> render() async {
try {
return await _delegate.render();
} catch (e) {
} catch (e, stackTrace) {
if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace);
throw getFirebaseAuthException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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>(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);
}
Expand All @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/firebase_auth/firebase_auth_web/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies:
web: ^1.0.0

dev_dependencies:
firebase_core_platform_interface: ^8.1.1
flutter_test:
sdk: flutter

Expand Down
Loading
Loading