π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Share two-factor recovery across web and mobile
Neeraj Gupta8bb53b653b4c
diff --git a/mobile/apps/auth/lib/main.dart b/mobile/apps/auth/lib/main.dartindex c802952e72..2b5bfa2499 100644--- a/mobile/apps/auth/lib/main.dart+++ b/mobile/apps/auth/lib/main.dart@@ -17,6 +17,8 @@ import 'package:ente_auth/services/preference_service.dart';import 'package:ente_auth/services/update_service.dart';import 'package:ente_auth/services/window_listener_service.dart';import 'package:ente_auth/src/rust/frb_generated.dart';+import 'package:ente_auth/src/rust/third_party/ente_frb_lib/accounts.dart'+ as accounts;import 'package:ente_auth/store/authenticator_db.dart';import 'package:ente_auth/store/code_display_store.dart';import 'package:ente_auth/store/code_store.dart';@@ -210,7 +212,11 @@ Future<void> _init() async {await Configuration.instance.init([AuthenticatorDB.instance]);await cleanupPickedImagesOnStartup(logger: _logger);await Network.instance.init(Configuration.instance);- await UserService.instance.init(Configuration.instance, const HomePage());+ await UserService.instance.init(+ Configuration.instance,+ const HomePage(),+ createAccountsClient: accounts.createAccountsClient,+ );await AuthenticatorService.instance.init();await BillingService.instance.init();await NotificationService.instance.init();diff --git a/mobile/apps/auth/test/ui/home/home_page_keyboard_test.dart b/mobile/apps/auth/test/ui/home/home_page_keyboard_test.dartindex c58125842c..7141a7cc45 100644--- a/mobile/apps/auth/test/ui/home/home_page_keyboard_test.dart+++ b/mobile/apps/auth/test/ui/home/home_page_keyboard_test.dart@@ -5,6 +5,8 @@ import 'package:ente_auth/core/configuration.dart';import 'package:ente_auth/ente_theme_data.dart';import 'package:ente_auth/services/authenticator_service.dart';import 'package:ente_auth/services/preference_service.dart';+import 'package:ente_auth/src/rust/third_party/ente_frb_lib/accounts.dart'+ as accounts;import 'package:ente_auth/store/code_display_store.dart';import 'package:ente_auth/store/code_store.dart';import 'package:ente_auth/store/offline_authenticator_db.dart';@@ -63,7 +65,11 @@ void main() {await Configuration.instance.init([]);databaseFactory = databaseFactoryFfi;await Network.instance.init(Configuration.instance);- await UserService.instance.init(Configuration.instance, const HomePage());+ await UserService.instance.init(+ Configuration.instance,+ const HomePage(),+ createAccountsClient: accounts.createAccountsClient,+ );await PreferenceService.instance.init();await AuthenticatorService.instance.init();await CodeStore.instance.init();diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dartindex f68b0b06e8..8b59ef5088 100644--- a/mobile/apps/locker/lib/main.dart+++ b/mobile/apps/locker/lib/main.dart@@ -38,6 +38,8 @@ import 'package:locker/services/trash/trash_service.dart';import 'package:locker/services/update_service.dart';import 'package:locker/src/rust/api/log.dart';import 'package:locker/src/rust/frb_generated.dart';+import 'package:locker/src/rust/third_party/ente_frb_lib/accounts.dart'+ as accounts;import 'package:locker/ui/pages/home_page.dart';import 'package:package_info_plus/package_info_plus.dart';import 'package:path_provider/path_provider.dart';@@ -189,6 +191,7 @@ Future<void> _init(bool bool, {String? via}) async {await UserService.instance.init(Configuration.instance,const HomePage(),+ createAccountsClient: accounts.createAccountsClient,installSourceHandler: InstallSourceHandler(hasInstallSource: installSourceService.hasInstallSource,autoAttributeSource: installSourceService.autoAttributeSource,diff --git a/mobile/apps/photos/lib/gateways/users/users_gateway.dart b/mobile/apps/photos/lib/gateways/users/users_gateway.dartindex e3d3fae555..b4d4a5be1b 100644--- a/mobile/apps/photos/lib/gateways/users/users_gateway.dart+++ b/mobile/apps/photos/lib/gateways/users/users_gateway.dart@@ -257,33 +257,6 @@ class UsersGateway {return response.data as Map<String, dynamic>;}- Future<Map<String, dynamic>> recoverTwoFactor({- required String sessionID,- required String twoFactorType,- }) async {- final response = await _publicDio.get(- "$_endpoint/users/two-factor/recover",- queryParameters: {"sessionID": sessionID, "twoFactorType": twoFactorType},- );- return response.data as Map<String, dynamic>;- }-- Future<Map<String, dynamic>> removeTwoFactor({- required String sessionID,- required String secret,- required String twoFactorType,- }) async {- final response = await _publicDio.post(- "$_endpoint/users/two-factor/remove",- data: {- "sessionID": sessionID,- "secret": secret,- "twoFactorType": twoFactorType,- },- );- return response.data as Map<String, dynamic>;- }-Future<Map<String, dynamic>> getTokenForPasskeySession(String sessionID,) async {diff --git a/mobile/apps/photos/lib/models/account/two_factor.dart b/mobile/apps/photos/lib/models/account/two_factor.dartdeleted file mode 100644index bebdbb27fe..0000000000--- a/mobile/apps/photos/lib/models/account/two_factor.dart+++ /dev/null@@ -1,10 +0,0 @@-enum TwoFactorType { totp, passkey }--String twoFactorTypeToString(TwoFactorType type) {- switch (type) {- case TwoFactorType.totp:- return "totp";- case TwoFactorType.passkey:- return "passkey";- }-}diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dartindex b5ed4567ca..d87a7e71a6 100644--- a/mobile/apps/photos/lib/services/account/user_service.dart+++ b/mobile/apps/photos/lib/services/account/user_service.dart@@ -3,8 +3,8 @@ import "dart:convert";import "dart:io";import "dart:math";-import 'package:bip39/bip39.dart' as bip39;import 'package:dio/dio.dart';+import "package:ente_base/models/two_factor.dart";import 'package:ente_crypto/ente_crypto.dart';import "package:ente_pure_utils/ente_pure_utils.dart";import "package:ente_strings/ente_strings.dart";@@ -12,7 +12,6 @@ import "package:flutter/foundation.dart";import 'package:flutter/material.dart';import 'package:logging/logging.dart';import 'package:photos/core/configuration.dart';-import 'package:photos/core/constants.dart';import 'package:photos/core/event_bus.dart';import "package:photos/events/account_configured_event.dart";import 'package:photos/events/signed_in_event.dart';@@ -25,12 +24,13 @@ import 'package:photos/gateways/users/models/set_keys_request.dart';import 'package:photos/gateways/users/models/set_recovery_key_request.dart';import "package:photos/gateways/users/models/srp.dart";import "package:photos/gateways/users/users_gateway.dart";-import "package:photos/models/account/two_factor.dart";import "package:photos/models/api/collection/user.dart";import 'package:photos/models/user_details.dart';import "package:photos/service_locator.dart";import "package:photos/services/collections_service.dart";import "package:photos/services/machine_learning/face_ml/person/person_service.dart";+import 'package:photos/src/rust/third_party/ente_frb_lib/accounts.dart'+ as accounts;import 'package:photos/ui/account/login_page.dart';import 'package:photos/ui/account/ott_verification_page.dart';import "package:photos/ui/account/passkey_page.dart";@@ -68,6 +68,7 @@ class UserService {final _logger = Logger((UserService).toString());final _config = Configuration.instance;late SharedPreferences _preferences;+ ({String origin, AccountsClient client})? _accountsClient;StreamSubscription<UserLoggedOutEvent>? _loggedOutEventSubscription;StreamSubscription<SignedInEvent>? _signedInEventSubscription;@@ -874,6 +875,25 @@ class UserService {}}+ AccountsClient _getAccountsClient() {+ final origin = endpointConfig.endpoint;+ if (_accountsClient?.origin != origin) {+ final services = ServiceLocator.instance;+ final client = accounts.createAccountsClient(+ config: AccountsClientConfig(+ origin: origin,+ clientPackage: services.packageInfo.packageName,+ clientVersion: services.packageInfo.version,+ userAgent:+ services.enteDio.options.headers[HttpHeaders.userAgentHeader]+ as String,+ ),+ );+ _accountsClient = (origin: origin, client: client);+ }+ return _accountsClient!.client;+ }+Future<void> recoverTwoFactor(BuildContext context,String sessionID,@@ -883,34 +903,31 @@ class UserService {await dialog.show();try {_logger.info("recovering two factor");- final responseData = await _gateway.recoverTwoFactor(- sessionID: sessionID,- twoFactorType: twoFactorTypeToString(type),+ final client = _getAccountsClient();+ final response = await client.getTwoFactorRecovery(+ sessionId: sessionID,+ twoFactorType: type,);-+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();+ }await dialog.hide();if (!context.mounted) return;// ignore: unawaited_futuresNavigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) {- return TwoFactorRecoveryPage(- type,- sessionID,- responseData["encryptedSecret"],- responseData["secretDecryptionNonce"],- );+ return TwoFactorRecoveryPage(client, type, sessionID, response);},),(route) => route.isFirst,);- } on DioException catch (e) {+ } catch (e) {await dialog.hide();_logger.severe('error while recovery 2fa', e);- if (e.response != null && e.response!.statusCode == 404) {- if (!context.mounted) return;+ if (!context.mounted) return;+ if (e == const AccountsError.sessionExpired()) {showToast(context, context.strings.sessionExpired);- if (!context.mounted) return;// ignore: unawaited_futuresNavigator.of(context).pushAndRemoveUntil(MaterialPageRoute(@@ -921,7 +938,6 @@ class UserService {(route) => route.isFirst,);} else {- if (!context.mounted) return;// ignore: unawaited_futuresshowAlertBottomSheet(context,@@ -930,18 +946,6 @@ class UserService {assetPath: 'assets/warning-grey.png',);}- } catch (e) {- _logger.severe('unexpected error while recovery 2fa', e);- await dialog.hide();- _logger.severe(e);- if (!context.mounted) return;- // ignore: unawaited_futures- showAlertBottomSheet(- context,- title: context.strings.oops,- message: context.strings.somethingWentWrongPleaseTryAgain,- assetPath: 'assets/warning-grey.png',- );} finally {await dialog.hide();}@@ -949,49 +953,28 @@ class UserService {Future<void> removeTwoFactor(BuildContext context,+ AccountsClient client,TwoFactorType type,String sessionID,String recoveryKey,- String encryptedSecret,- String secretDecryptionNonce,+ TwoFactorRecoveryResponse recoveryResponse,) async {final dialog = createProgressDialog(context, context.strings.pleaseWait);await dialog.show();- String secret;try {- if (recoveryKey.contains(' ')) {- if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {- throw AssertionError(- 'recovery code should have $mnemonicKeyWordCount words',- );- }- recoveryKey = bip39.mnemonicToEntropy(recoveryKey);+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();}- secret = CryptoUtil.bin2base64(- await CryptoUtil.decrypt(- CryptoUtil.base642bin(encryptedSecret),- CryptoUtil.hex2bin(recoveryKey.trim()),- CryptoUtil.base642bin(secretDecryptionNonce),- ),+ final response = await client.recoverTwoFactor(+ twoFactorType: type,+ sessionId: sessionID,+ recoveryResponse: recoveryResponse,+ recoveryKey: recoveryKey,);- } catch (e) {- await dialog.hide();- if (!context.mounted) return;- await showAlertBottomSheet(- context,- title: context.strings.incorrectRecoveryKey,- message: context.strings.theRecoveryKeyYouEnteredIsIncorrect,- assetPath: 'assets/warning-grey.png',- );- return;- }- try {- final responseData = await _gateway.removeTwoFactor(- sessionID: sessionID,- secret: secret,- twoFactorType: twoFactorTypeToString(type),- );- await _saveConfiguration(responseData);+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();+ }+ await _saveConfiguration(response.toMap());await dialog.hide();if (context.mounted) {showShortToast(@@ -1008,13 +991,19 @@ class UserService {(route) => route.isFirst,);}- } on DioException catch (e) {+ } catch (e) {await dialog.hide();_logger.severe("error during recovery", e);- if (e.response != null && e.response!.statusCode == 404) {- if (!context.mounted) return;+ if (!context.mounted) return;+ if (e == const AccountsError.incorrectRecoveryKey()) {+ await showAlertBottomSheet(+ context,+ title: context.strings.incorrectRecoveryKey,+ message: context.strings.theRecoveryKeyYouEnteredIsIncorrect,+ assetPath: 'assets/warning-grey.png',+ );+ } else if (e == const AccountsError.sessionExpired()) {showToast(context, context.strings.sessionExpired);- if (!context.mounted) return;// ignore: unawaited_futuresNavigator.of(context).pushAndRemoveUntil(MaterialPageRoute(@@ -1025,7 +1014,6 @@ class UserService {(route) => route.isFirst,);} else {- if (!context.mounted) return;// ignore: unawaited_futuresshowAlertBottomSheet(context,@@ -1034,18 +1022,6 @@ class UserService {assetPath: 'assets/warning-grey.png',);}- } catch (e) {- await dialog.hide();- _logger.severe('unexpcted error during recovery', e);-- if (!context.mounted) return;- // ignore: unawaited_futures- showAlertBottomSheet(- context,- title: context.strings.oops,- message: context.strings.somethingWentWrongPleaseTryAgain,- assetPath: 'assets/warning-grey.png',- );} finally {await dialog.hide();}diff --git a/mobile/apps/photos/lib/ui/account/passkey_page.dart b/mobile/apps/photos/lib/ui/account/passkey_page.dartindex 8da11eb681..91c636f0e9 100644--- a/mobile/apps/photos/lib/ui/account/passkey_page.dart+++ b/mobile/apps/photos/lib/ui/account/passkey_page.dart@@ -2,6 +2,7 @@ import "dart:async";import 'dart:convert';import "package:app_links/app_links.dart";+import "package:ente_base/models/two_factor.dart";import "package:ente_components/ente_components.dart";import "package:ente_pure_utils/ente_pure_utils.dart";import "package:ente_strings/ente_strings.dart";@@ -9,7 +10,6 @@ import 'package:flutter/material.dart';import 'package:logging/logging.dart';import 'package:photos/core/configuration.dart';import "package:photos/core/errors.dart";-import "package:photos/models/account/two_factor.dart";import 'package:photos/services/account/user_service.dart';import "package:photos/ui/account/onboarding_page_scaffold.dart";import "package:photos/ui/account/two_factor_authentication_page.dart";diff --git a/mobile/apps/photos/lib/ui/account/two_factor_authentication_page.dart b/mobile/apps/photos/lib/ui/account/two_factor_authentication_page.dartindex 0fdd862160..83c8188909 100644--- a/mobile/apps/photos/lib/ui/account/two_factor_authentication_page.dart+++ b/mobile/apps/photos/lib/ui/account/two_factor_authentication_page.dart@@ -1,8 +1,8 @@+import "package:ente_base/models/two_factor.dart";import 'package:ente_components/ente_components.dart';import "package:ente_strings/ente_strings.dart";import 'package:flutter/material.dart';import 'package:flutter/services.dart';-import "package:photos/models/account/two_factor.dart";import 'package:photos/services/account/user_service.dart';import "package:photos/ui/account/onboarding_page_scaffold.dart";import 'package:photos/ui/lifecycle_event_handler.dart';diff --git a/mobile/apps/photos/lib/ui/account/two_factor_recovery_page.dart b/mobile/apps/photos/lib/ui/account/two_factor_recovery_page.dartindex 9c674871e4..000b2e01d5 100644--- a/mobile/apps/photos/lib/ui/account/two_factor_recovery_page.dart+++ b/mobile/apps/photos/lib/ui/account/two_factor_recovery_page.dart@@ -1,21 +1,21 @@+import "package:ente_base/models/two_factor.dart";import "package:ente_components/ente_components.dart";import "package:ente_strings/ente_strings.dart";import 'package:flutter/material.dart';-import "package:photos/models/account/two_factor.dart";import 'package:photos/services/account/user_service.dart';import "package:photos/ui/components/alert_bottom_sheet.dart";class TwoFactorRecoveryPage extends StatefulWidget {+ final AccountsClient client;final String sessionID;- final String encryptedSecret;- final String secretDecryptionNonce;+ final TwoFactorRecoveryResponse recoveryResponse;final TwoFactorType type;const TwoFactorRecoveryPage(+ this.client,this.type,this.sessionID,- this.encryptedSecret,- this.secretDecryptionNonce, {+ this.recoveryResponse, {super.key,});@@ -70,11 +70,11 @@ class _TwoFactorRecoveryPageState extends State<TwoFactorRecoveryPage> {FocusScope.of(context).unfocus();await UserService.instance.removeTwoFactor(context,+ widget.client,widget.type,widget.sessionID,_recoveryKeyController.text,- widget.encryptedSecret,- widget.secretDecryptionNonce,+ widget.recoveryResponse,);}: null,diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yamlindex bc2023606e..98e1841fe4 100644--- a/mobile/apps/photos/pubspec.yaml+++ b/mobile/apps/photos/pubspec.yaml@@ -38,6 +38,8 @@ dependencies:path: ../../packages/account_deletionente_background_manager:path: plugins/ente_background_manager+ ente_base:+ path: ../../packages/baseente_cast:path: plugins/ente_castente_components:diff --git a/mobile/packages/accounts/lib/ente_accounts.dart b/mobile/packages/accounts/lib/ente_accounts.dartindex cf4a6b37bf..5d94375d04 100644--- a/mobile/packages/accounts/lib/ente_accounts.dart+++ b/mobile/packages/accounts/lib/ente_accounts.dart@@ -1,10 +1,11 @@+export 'package:ente_base/models/two_factor.dart';+export 'models/bonus.dart';export 'models/sessions.dart';export 'models/set_keys_request.dart';export 'models/set_recovery_key_request.dart';export 'models/srp.dart';export 'models/subscription.dart';-export 'models/two_factor.dart';export 'models/user_details.dart';export 'pages/change_email_dialog.dart';diff --git a/mobile/packages/accounts/lib/models/two_factor.dart b/mobile/packages/accounts/lib/models/two_factor.dartdeleted file mode 100644index bebdbb27fe..0000000000--- a/mobile/packages/accounts/lib/models/two_factor.dart+++ /dev/null@@ -1,10 +0,0 @@-enum TwoFactorType { totp, passkey }--String twoFactorTypeToString(TwoFactorType type) {- switch (type) {- case TwoFactorType.totp:- return "totp";- case TwoFactorType.passkey:- return "passkey";- }-}diff --git a/mobile/packages/accounts/lib/pages/two_factor_recovery_page.dart b/mobile/packages/accounts/lib/pages/two_factor_recovery_page.dartindex 3ea15e20d2..c99a6b7d2b 100644--- a/mobile/packages/accounts/lib/pages/two_factor_recovery_page.dart+++ b/mobile/packages/accounts/lib/pages/two_factor_recovery_page.dart@@ -7,16 +7,16 @@ import 'package:ente_utils/email_util.dart';import 'package:flutter/material.dart';class TwoFactorRecoveryPage extends StatefulWidget {+ final AccountsClient client;final String sessionID;- final String encryptedSecret;- final String secretDecryptionNonce;+ final TwoFactorRecoveryResponse recoveryResponse;final TwoFactorType type;const TwoFactorRecoveryPage(+ this.client,this.type,this.sessionID,- this.encryptedSecret,- this.secretDecryptionNonce, {+ this.recoveryResponse, {super.key,});@@ -30,11 +30,11 @@ class _TwoFactorRecoveryPageState extends State<TwoFactorRecoveryPage> {Future<void> _onRecover() async {await UserService.instance.removeTwoFactor(context,+ widget.client,widget.type,widget.sessionID,_recoveryKey.text,- widget.encryptedSecret,- widget.secretDecryptionNonce,+ widget.recoveryResponse,);}diff --git a/mobile/packages/accounts/lib/services/user_service.dart b/mobile/packages/accounts/lib/services/user_service.dartindex 1a6a0a9397..1894b100eb 100644--- a/mobile/packages/accounts/lib/services/user_service.dart+++ b/mobile/packages/accounts/lib/services/user_service.dart@@ -3,14 +3,12 @@ import "dart:convert";import "dart:io";import "dart:math";-import 'package:bip39/bip39.dart' as bip39;import 'package:dio/dio.dart';import 'package:ente_accounts/models/errors.dart';import 'package:ente_accounts/models/sessions.dart';import 'package:ente_accounts/models/set_keys_request.dart';import 'package:ente_accounts/models/set_recovery_key_request.dart';import 'package:ente_accounts/models/srp.dart';-import 'package:ente_accounts/models/two_factor.dart';import 'package:ente_accounts/models/user_details.dart';import 'package:ente_accounts/pages/login_page.dart';import 'package:ente_accounts/pages/ott_verification_page.dart';@@ -23,8 +21,8 @@ import 'package:ente_accounts/pages/two_factor_recovery_page.dart';import 'package:ente_accounts/services/install_source_handler.dart';import 'package:ente_base/models/key_attributes.dart';import 'package:ente_base/models/key_gen_result.dart';+import 'package:ente_base/models/two_factor.dart';import 'package:ente_configuration/base_configuration.dart';-import 'package:ente_configuration/constants.dart';import 'package:ente_crypto_api/ente_crypto_api.dart';import 'package:ente_events/event_bus.dart';import 'package:ente_events/models/user_details_changed_event.dart';@@ -60,6 +58,8 @@ class UserService {late ValueNotifier<String?> emailValueNotifier;late BaseConfiguration _config;late BaseHomePage _homePage;+ late CreateAccountsClient _createAccountsClient;+ ({String origin, AccountsClient client})? _accountsClient;InstallSourceHandler? _installSourceHandler;UserService._privateConstructor();@@ -69,10 +69,13 @@ class UserService {Future<void> init(BaseConfiguration config,BaseHomePage homePage, {+ required CreateAccountsClient createAccountsClient,InstallSourceHandler? installSourceHandler,}) async {_config = config;_homePage = homePage;+ _createAccountsClient = createAccountsClient;+ _accountsClient = null;_installSourceHandler = installSourceHandler;emailValueNotifier = ValueNotifier<String?>(config.getEmail());_preferences = await SharedPreferences.getInstance();@@ -938,6 +941,23 @@ class UserService {}}+ AccountsClient _getAccountsClient() {+ final origin = _config.getHttpEndpoint();+ if (_accountsClient?.origin != origin) {+ final headers = _enteDio.options.headers;+ final client = _createAccountsClient(+ config: AccountsClientConfig(+ origin: origin,+ clientPackage: headers['X-Client-Package'] as String,+ clientVersion: headers['X-Client-Version'] as String,+ userAgent: headers[HttpHeaders.userAgentHeader] as String,+ ),+ );+ _accountsClient = (origin: origin, client: client);+ }+ return _accountsClient!.client;+ }+Future<void> recoverTwoFactor(BuildContext context,String sessionID,@@ -946,39 +966,33 @@ class UserService {final dialog = createProgressDialog(context, context.strings.pleaseWait);await dialog.show();try {- final response = await _dio.get(- "${_config.getHttpEndpoint()}/users/two-factor/recover",- queryParameters: {- "sessionID": sessionID,- "twoFactorType": twoFactorTypeToString(type),- },+ final client = _getAccountsClient();+ final response = await client.getTwoFactorRecovery(+ sessionId: sessionID,+ twoFactorType: type,);+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();+ }await dialog.hide();- if (response.statusCode == 200) {- if (context.mounted) {- // ignore: unawaited_futures- Navigator.of(context).pushAndRemoveUntil(- MaterialPageRoute(- builder: (BuildContext context) {- return TwoFactorRecoveryPage(- type,- sessionID,- response.data["encryptedSecret"],- response.data["secretDecryptionNonce"],- );- },- ),- (route) => route.isFirst,- );- }+ if (context.mounted) {+ // ignore: unawaited_futures+ Navigator.of(context).pushAndRemoveUntil(+ MaterialPageRoute(+ builder: (BuildContext context) {+ return TwoFactorRecoveryPage(client, type, sessionID, response);+ },+ ),+ (route) => route.isFirst,+ );}- } on DioException catch (e) {+ } catch (e) {await dialog.hide();_logger.severe(e);if (!context.mounted) {return;}- if (e.response != null && e.response!.statusCode == 404) {+ if (e == const AccountsError.sessionExpired()) {showToast(context, context.strings.sessionExpired);// ignore: unawaited_futuresNavigator.of(context).pushAndRemoveUntil(@@ -998,18 +1012,6 @@ class UserService {assetPath: 'assets/warning-grey.png',);}- } catch (e) {- await dialog.hide();- _logger.severe(e);- if (context.mounted) {- // ignore: unawaited_futures- showAlertBottomSheet(- context,- title: context.strings.oops,- message: context.strings.somethingWentWrongPleaseTryAgain,- assetPath: 'assets/warning-grey.png',- );- }} finally {await dialog.hide();}@@ -1017,79 +1019,58 @@ class UserService {Future<void> removeTwoFactor(BuildContext context,+ AccountsClient client,TwoFactorType type,String sessionID,String recoveryKey,- String encryptedSecret,- String secretDecryptionNonce,+ TwoFactorRecoveryResponse recoveryResponse,) async {final dialog = createProgressDialog(context, context.strings.pleaseWait);await dialog.show();- String secret;try {- if (recoveryKey.contains(' ')) {- if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {- throw AssertionError(- 'recovery code should have $mnemonicKeyWordCount words',- );- }- recoveryKey = bip39.mnemonicToEntropy(recoveryKey);+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();}- secret = CryptoUtil.bin2base64(- await CryptoUtil.decrypt(- CryptoUtil.base642bin(encryptedSecret),- CryptoUtil.hex2bin(recoveryKey.trim()),- CryptoUtil.base642bin(secretDecryptionNonce),- ),+ final response = await client.recoverTwoFactor(+ twoFactorType: type,+ sessionId: sessionID,+ recoveryResponse: recoveryResponse,+ recoveryKey: recoveryKey,);- } catch (e) {- await dialog.hide();- if (!context.mounted) {- return;+ if (client != _getAccountsClient()) {+ throw const AccountsError.sessionExpired();}- await showAlertBottomSheet(- context,- title: context.strings.incorrectRecoveryKey,- message: context.strings.theRecoveryKeyYouEnteredIsIncorrect,- assetPath: 'assets/warning-grey.png',- );- return;- }- try {- final response = await _dio.post(- "${_config.getHttpEndpoint()}/users/two-factor/remove",- data: {- "sessionID": sessionID,- "secret": secret,- "twoFactorType": twoFactorTypeToString(type),- },- );+ await _saveConfiguration(response.toMap());await dialog.hide();- if (response.statusCode == 200) {- await _saveConfiguration(response);- if (context.mounted) {- showShortToast(- context,- context.strings.twofactorAuthenticationSuccessfullyReset,- );- // ignore: unawaited_futures- Navigator.of(context).pushAndRemoveUntil(- MaterialPageRoute(- builder: (BuildContext context) {- return PasswordReentryPage(_config, _homePage);- },- ),- (route) => route.isFirst,- );- }+ if (context.mounted) {+ showShortToast(+ context,+ context.strings.twofactorAuthenticationSuccessfullyReset,+ );+ // ignore: unawaited_futures+ Navigator.of(context).pushAndRemoveUntil(+ MaterialPageRoute(+ builder: (BuildContext context) {+ return PasswordReentryPage(_config, _homePage);+ },+ ),+ (route) => route.isFirst,+ );}- } on DioException catch (e) {+ } catch (e) {await dialog.hide();_logger.severe(e);if (!context.mounted) {return;}- if (e.response != null && e.response!.statusCode == 404) {+ if (e == const AccountsError.incorrectRecoveryKey()) {+ await showAlertBottomSheet(+ context,+ title: context.strings.incorrectRecoveryKey,+ message: context.strings.theRecoveryKeyYouEnteredIsIncorrect,+ assetPath: 'assets/warning-grey.png',+ );+ } else if (e == const AccountsError.sessionExpired()) {showToast(context, "Session expired");// ignore: unawaited_futuresNavigator.of(context).pushAndRemoveUntil(@@ -1109,18 +1090,6 @@ class UserService {assetPath: 'assets/warning-grey.png',);}- } catch (e) {- await dialog.hide();- _logger.severe(e);- if (context.mounted) {- // ignore: unawaited_futures- showAlertBottomSheet(- context,- title: context.strings.oops,- message: context.strings.somethingWentWrongPleaseTryAgain,- assetPath: 'assets/warning-grey.png',- );- }} finally {await dialog.hide();}diff --git a/mobile/packages/base/lib/models/two_factor.dart b/mobile/packages/base/lib/models/two_factor.dartnew file mode 100644index 0000000000..f7bf10e913--- /dev/null+++ b/mobile/packages/base/lib/models/two_factor.dart@@ -0,0 +1,36 @@+import 'package:ente_frb/accounts.dart';++export 'package:ente_frb/accounts.dart'+ show+ AccountsClient,+ AccountsClientConfig,+ AccountsError,+ TwoFactorAuthorizationResponse,+ TwoFactorRecoveryResponse,+ TwoFactorType;++typedef CreateAccountsClient =+ AccountsClient Function({required AccountsClientConfig config});++extension TwoFactorAuthorizationResponseMap on TwoFactorAuthorizationResponse {+ Map<String, dynamic> toMap() => {+ 'id': id.toInt(),+ 'encryptedToken': encryptedToken,+ 'keyAttributes': {+ 'kekSalt': keyAttributes.kekSalt,+ 'encryptedKey': keyAttributes.encryptedKey,+ 'keyDecryptionNonce': keyAttributes.keyDecryptionNonce,+ 'publicKey': keyAttributes.publicKey,+ 'encryptedSecretKey': keyAttributes.encryptedSecretKey,+ 'secretKeyDecryptionNonce': keyAttributes.secretKeyDecryptionNonce,+ 'memLimit': keyAttributes.memLimit.toInt(),+ 'opsLimit': keyAttributes.opsLimit,+ 'masterKeyEncryptedWithRecoveryKey':+ keyAttributes.masterKeyEncryptedWithRecoveryKey,+ 'masterKeyDecryptionNonce': keyAttributes.masterKeyDecryptionNonce,+ 'recoveryKeyEncryptedWithMasterKey':+ keyAttributes.recoveryKeyEncryptedWithMasterKey,+ 'recoveryKeyDecryptionNonce': keyAttributes.recoveryKeyDecryptionNonce,+ },+ };+}diff --git a/mobile/packages/base/pubspec.yaml b/mobile/packages/base/pubspec.yamlindex 3d2b4c667f..8402571e0b 100644--- a/mobile/packages/base/pubspec.yaml+++ b/mobile/packages/base/pubspec.yaml@@ -7,6 +7,8 @@ environment:flutter: ">=1.17.0"dependencies:+ ente_frb:+ path: ../frbflutter:sdk: flutterdiff --git a/rust/bindings/frb/lib/src/accounts.rs b/rust/bindings/frb/lib/src/accounts.rsnew file mode 100644index 0000000000..848176c0f0--- /dev/null+++ b/rust/bindings/frb/lib/src/accounts.rs@@ -0,0 +1,19 @@+use flutter_rust_bridge::frb;++pub mod types;+pub use types::{AccountsClient, AccountsClientConfig, AccountsError};++#[frb(sync)]+pub fn create_accounts_client(+ config: AccountsClientConfig,+) -> Result<AccountsClient, AccountsError> {+ Ok(AccountsClient(ente_accounts::AccountsClient::new(+ ente_accounts::AccountsClientConfig {+ origin: config.origin,+ client_package: config.client_package,+ client_version: config.client_version,+ user_agent: config.user_agent,+ auth_token: None,+ },+ )?))+}diff --git a/rust/bindings/frb/lib/src/accounts/types.rs b/rust/bindings/frb/lib/src/accounts/types.rsnew file mode 100644index 0000000000..26abd35142--- /dev/null+++ b/rust/bindings/frb/lib/src/accounts/types.rs@@ -0,0 +1,102 @@+use ente_accounts::{AccountsClient as InnerClient, Error, lifecycle};+pub use ente_accounts::{+ auth::KeyAttributes,+ models::{TwoFactorAuthorizationResponse, TwoFactorRecoveryResponse, TwoFactorType},+};+use flutter_rust_bridge::frb;++#[frb(non_opaque)]+pub enum AccountsError {+ IncorrectRecoveryKey,+ SessionExpired,+ Other { message: String },+}++impl From<Error> for AccountsError {+ fn from(error: Error) -> Self {+ match error {+ Error::IncorrectRecoveryKey => Self::IncorrectRecoveryKey,+ Error::Http(ref http) if http.status_code() == Some(404) => Self::SessionExpired,+ _ => Self::Other {+ message: ente_core::error::chain(&error),+ },+ }+ }+}++#[frb(non_opaque)]+pub struct AccountsClientConfig {+ pub origin: String,+ pub client_package: String,+ pub client_version: Option<String>,+ pub user_agent: Option<String>,+}++#[frb(opaque)]+pub struct AccountsClient(pub(crate) InnerClient);++impl AccountsClient {+ pub async fn get_two_factor_recovery(+ &self,+ two_factor_type: TwoFactorType,+ session_id: String,+ ) -> Result<TwoFactorRecoveryResponse, AccountsError> {+ self.0+ .get_two_factor_recovery(&session_id, two_factor_type)+ .await+ .map_err(Into::into)+ }++ pub async fn recover_two_factor(+ &self,+ two_factor_type: TwoFactorType,+ session_id: String,+ recovery_response: TwoFactorRecoveryResponse,+ recovery_key: String,+ ) -> Result<TwoFactorAuthorizationResponse, AccountsError> {+ lifecycle::recover_two_factor(+ &self.0,+ two_factor_type,+ &session_id,+ &recovery_response,+ &recovery_key,+ )+ .await+ .map_err(Into::into)+ }+}++#[frb(mirror(TwoFactorType))]+pub enum _TwoFactorType {+ Totp,+ Passkey,+}++#[frb(mirror(TwoFactorRecoveryResponse))]+pub struct _TwoFactorRecoveryResponse {+ pub encrypted_secret: String,+ pub secret_decryption_nonce: String,+}++#[frb(mirror(TwoFactorAuthorizationResponse))]+pub struct _TwoFactorAuthorizationResponse {+ pub id: i64,+ pub key_attributes: KeyAttributes,+ pub encrypted_token: String,+}++#[frb(mirror(KeyAttributes))]+pub struct _KeyAttributes {+ pub kek_salt: String,+ pub encrypted_key: String,+ pub key_decryption_nonce: String,+ pub public_key: String,+ pub encrypted_secret_key: String,+ pub secret_key_decryption_nonce: String,+ pub mem_limit: u64,+ pub ops_limit: u32,+ pub master_key_encrypted_with_recovery_key: Option<String>,+ pub master_key_decryption_nonce: Option<String>,+ pub recovery_key_encrypted_with_master_key: Option<String>,+ pub recovery_key_decryption_nonce: Option<String>,+}diff --git a/rust/bindings/frb/lib/src/lib.rs b/rust/bindings/frb/lib/src/lib.rsindex c50663a5ad..324dac6119 100644--- a/rust/bindings/frb/lib/src/lib.rs+++ b/rust/bindings/frb/lib/src/lib.rs@@ -1,4 +1,5 @@pub mod account_deletion;+pub mod accounts;#[cfg(feature = "contacts")]pub mod contacts;#[cfg(feature = "legacy")]diff --git a/rust/bindings/wasm/lib/Cargo.toml b/rust/bindings/wasm/lib/Cargo.tomlindex 8b69ade111..b50be7d25b 100644--- a/rust/bindings/wasm/lib/Cargo.toml+++ b/rust/bindings/wasm/lib/Cargo.toml@@ -19,7 +19,7 @@ crypto-seal = ["crypto"]legacy = ["session", "dep:ente-legacy", "dep:wasm-bindgen-futures"]location = ["dep:ente-location", "dep:serde", "dep:serde-wasm-bindgen", "dep:tsify"]locker = ["session", "dep:ente-locker"]-prelogin = ["accounts", "crypto"]+prelogin = ["accounts", "crypto", "dep:wasm-bindgen-futures"]session = ["dep:ente-accounts","dep:serde",diff --git a/rust/bindings/wasm/lib/src/accounts.rs b/rust/bindings/wasm/lib/src/accounts.rsindex 43169a12b5..315f97cb23 100644--- a/rust/bindings/wasm/lib/src/accounts.rs+++ b/rust/bindings/wasm/lib/src/accounts.rs@@ -5,18 +5,29 @@ use serde_wasm_bindgen as swb;use tsify::Tsify;use wasm_bindgen::prelude::*;+#[cfg(feature = "prelogin")]+mod client;+#[derive(Debug, thiserror::Error)]pub enum Error {#[error(transparent)]Accounts(#[from] ente_accounts::Error),#[error(transparent)]Serde(#[from] swb::Error),+ #[error(transparent)]+ Input(#[from] tsify::Error),}impl Error {fn name(&self) -> Option<&'static str> {match self {Self::Accounts(ente_accounts::Error::InsufficientMemory) => Some("insufficient_memory"),+ Self::Accounts(ente_accounts::Error::IncorrectRecoveryKey) => {+ Some("incorrect_recovery_key")+ }+ Self::Accounts(ente_accounts::Error::Http(http)) if http.status_code() == Some(404) => {+ Some("session_expired")+ }_ => None,}}@@ -24,7 +35,13 @@ impl Error {impl From<Error> for JsValue {fn from(error: Error) -> Self {- crate::js_error(&error, error.name())+ let value = crate::js_error(&error, error.name());+ if let Error::Accounts(ente_accounts::Error::Http(http)) = &error+ && let Some(status) = http.status_code()+ {+ let _ = js_sys::Reflect::set(&value, &"status".into(), &status.into());+ }+ value}}diff --git a/rust/bindings/wasm/lib/src/accounts/client.rs b/rust/bindings/wasm/lib/src/accounts/client.rsnew file mode 100644index 0000000000..00df9cacc9--- /dev/null+++ b/rust/bindings/wasm/lib/src/accounts/client.rs@@ -0,0 +1,68 @@+use ente_accounts::lifecycle;+use serde::Deserialize;+use serde_wasm_bindgen as swb;+use tsify::{Ts, Tsify};+use wasm_bindgen::prelude::*;++use super::Error;++#[derive(Deserialize, Tsify)]+#[serde(rename_all = "camelCase")]+pub struct AccountsClientConfig {+ origin: String,+ client_package: String,+ #[tsify(optional)]+ client_version: Option<String>,+}++#[wasm_bindgen]+pub struct AccountsClient(ente_accounts::AccountsClient);++#[wasm_bindgen(js_name = createAccountsClient)]+pub fn create_accounts_client(config: Ts<AccountsClientConfig>) -> Result<AccountsClient, Error> {+ let config = config.to_rust()?;+ Ok(AccountsClient(ente_accounts::AccountsClient::new(+ ente_accounts::AccountsClientConfig {+ origin: config.origin,+ client_package: config.client_package,+ client_version: config.client_version,+ user_agent: None,+ auth_token: None,+ },+ )?))+}++#[wasm_bindgen(js_name = getTwoFactorRecovery, unchecked_return_type = "unknown")]+pub async fn get_two_factor_recovery(+ client: &AccountsClient,+ two_factor_type: &str,+ session_id: &str,+) -> Result<JsValue, Error> {+ let response = client+ .0+ .get_two_factor_recovery(+ session_id,+ swb::from_value(JsValue::from_str(two_factor_type))?,+ )+ .await?;+ swb::to_value(&response).map_err(Into::into)+}++#[wasm_bindgen(js_name = recoverTwoFactor, unchecked_return_type = "unknown")]+pub async fn recover_two_factor(+ client: &AccountsClient,+ two_factor_type: &str,+ session_id: &str,+ #[wasm_bindgen(unchecked_param_type = "unknown")] recovery_response: JsValue,+ recovery_key: &str,+) -> Result<JsValue, Error> {+ let response = lifecycle::recover_two_factor(+ &client.0,+ swb::from_value(JsValue::from_str(two_factor_type))?,+ session_id,+ &swb::from_value(recovery_response)?,+ recovery_key,+ )+ .await?;+ swb::to_value(&response).map_err(Into::into)+}diff --git a/rust/crates/accounts/src/lifecycle/tests.rs b/rust/crates/accounts/src/lifecycle/tests.rsindex b2555866b7..dfcaf9ec59 100644--- a/rust/crates/accounts/src/lifecycle/tests.rs+++ b/rust/crates/accounts/src/lifecycle/tests.rs@@ -192,14 +192,26 @@ async fn two_factor_recovery_preserves_secret_encoding() {.create_async().await;+ let envelope = TwoFactorRecoveryResponse {+ encrypted_secret: b64::encode(&encrypted.encrypted_data),+ secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),+ };+ assert!(matches!(+ recover_two_factor(+ &client,+ factor,+ "recovery-session",+ &envelope,+ &hex::encode(crypto::Key::generate().as_bytes()),+ )+ .await,+ Err(Error::IncorrectRecoveryKey)+ ));recover_two_factor(&client,factor,"recovery-session",- &TwoFactorRecoveryResponse {- encrypted_secret: b64::encode(&encrypted.encrypted_data),- secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),- },+ &envelope,&recovery_key_hex,).awaitdiff --git a/rust/crates/accounts/src/models.rs b/rust/crates/accounts/src/models.rsindex 35a397ba42..5d851370f3 100644--- a/rust/crates/accounts/src/models.rs+++ b/rust/crates/accounts/src/models.rs@@ -326,7 +326,7 @@ pub struct TwoFactorStatusResponse {pub status: bool,}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum TwoFactorType {Totp,diff --git a/rust/tools/codegen/src/main.rs b/rust/tools/codegen/src/main.rsindex 1638e41429..89f696e42d 100644--- a/rust/tools/codegen/src/main.rs+++ b/rust/tools/codegen/src/main.rs@@ -183,8 +183,8 @@ fn generate_frb(target: FrbTarget) -> Result<(), DynError> {fs::remove_dir_all(&generated_dir)?;}generate_frb_package(&package_dir)?;- for name in ["account_deletion", "contacts", "legacy"] {- if *app == "auth" && name != "account_deletion" {+ for name in ["account_deletion", "accounts", "contacts", "legacy"] {+ if *app == "auth" && matches!(name, "contacts" | "legacy") {continue;}let types_path = package_dirdiff --git a/web/packages/accounts/pages/two-factor/recover.tsx b/web/packages/accounts/pages/two-factor/recover.tsxindex 400ea72688..139a845741 100644--- a/web/packages/accounts/pages/two-factor/recover.tsx+++ b/web/packages/accounts/pages/two-factor/recover.tsx@@ -5,14 +5,14 @@ import { savedPartialLocalUser } from "ente-accounts/services/accounts-db";import {getRecoverTwoFactor,recoverTwoFactorFinish,- type TwoFactorRecoveryResponse,+ type TwoFactorRecovery,type TwoFactorType,} from "ente-accounts/services/user";import { LoadingIndicator } from "ente-base/components/loaders";import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";import type { SingleInputFormProps } from "ente-base/components/SingleInputForm";import { useBaseContext } from "ente-base/context";-import { isHTTP4xxError, isHTTPErrorWithStatus } from "ente-base/http";+import { isNamedError } from "ente-base/error";import log from "ente-base/log";import { t } from "i18next";import { useRouter } from "next/router";@@ -34,9 +34,9 @@ const Page: React.FC<RecoverPageProps> = ({ twoFactorType = "totp" }) => {const { logout, showMiniDialog, onGenericError } = useBaseContext();const [sessionID, setSessionID] = useState<string | undefined>(undefined);- const [recoveryResponse, setRecoveryResponse] = useState<- TwoFactorRecoveryResponse | undefined- >(undefined);+ const [recovery, setRecovery] = useState<TwoFactorRecovery | undefined>(+ undefined,+ );const router = useRouter();@@ -77,14 +77,22 @@ const Page: React.FC<RecoverPageProps> = ({ twoFactorType = "totp" }) => {} else {setSessionID(sessionID);try {- setRecoveryResponse(+ setRecovery(await getRecoverTwoFactor(twoFactorType, sessionID),);} catch (e) {log.error("Second factor recovery page setup failed", e);- if (isHTTPErrorWithStatus(e, 404)) {+ const status =+ e instanceof Error && "status" in e+ ? e.status+ : undefined;+ if (isNamedError(e, "session_expired")) {logout();- } else if (isHTTP4xxError(e)) {+ } else if (+ typeof status === "number" &&+ status >= 400 &&+ status <= 499+ ) {showContactSupportDialog({ action: router.back });} else {onGenericError(e);@@ -102,21 +110,25 @@ const Page: React.FC<RecoverPageProps> = ({ twoFactorType = "totp" }) => {const handleSubmit: SingleInputFormProps["onSubmit"] | undefined = useMemo(() =>- sessionID && recoveryResponse+ sessionID && recovery? (recoveryKeyMnemonic, setFieldError) =>recoverTwoFactorFinish(twoFactorType,sessionID,- recoveryResponse,+ recovery,recoveryKeyMnemonic,).then(() => router.push("/credentials")).catch((e: unknown) => {log.error("Second factor recovery failed", e);- setFieldError(t("incorrect_recovery_key"));+ if (isNamedError(e, "session_expired")) {+ logout();+ } else {+ setFieldError(t("incorrect_recovery_key"));+ }}): undefined,- [twoFactorType, router, sessionID, recoveryResponse],+ [twoFactorType, router, sessionID, recovery, logout],);if (!handleSubmit) {diff --git a/web/packages/accounts/services/accounts-client.ts b/web/packages/accounts/services/accounts-client.tsnew file mode 100644index 0000000000..1a3e34be00--- /dev/null+++ b/web/packages/accounts/services/accounts-client.ts@@ -0,0 +1,21 @@+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";+import { apiOrigin } from "ente-base/origins";+import { createAccountsClient, type AccountsClient } from "ente-prelogin-wasm";++let current: { origin: string; client: Promise<AccountsClient> } | undefined;++export const getAccountsClient = async () => {+ const origin = await apiOrigin();+ if (current?.origin !== origin) {+ const client = createAccountsClient({+ origin,+ clientPackage: clientPackageName,+ ...(isDesktop && { clientVersion: desktopAppVersion }),+ }).catch((error: unknown) => {+ if (current?.client === client) current = undefined;+ throw error;+ });+ current = { origin, client };+ }+ return current.client;+};diff --git a/web/packages/accounts/services/user.ts b/web/packages/accounts/services/user.tsindex 3cbd4e9961..049f92c454 100644--- a/web/packages/accounts/services/user.ts+++ b/web/packages/accounts/services/user.ts@@ -16,6 +16,7 @@ import {toB64URLSafe,} from "ente-accounts/services/crypto";import { generateInteractiveKeyAttributes } from "ente-accounts/services/key-attributes";+import { namedError } from "ente-base/error";import {authenticatedRequestHeaders,ensureOk,@@ -27,10 +28,15 @@ import {saveAuthToken,savedAuthToken,} from "ente-base/token";+import {+ getTwoFactorRecovery,+ recoverTwoFactor,+ type AccountsClient,+} from "ente-prelogin-wasm";import { nullToUndefined } from "ente-utils/transform";import { z } from "zod";+import { getAccountsClient } from "./accounts-client";import { clearInflightPasskeySessionID } from "./passkey";-import { recoveryKeyFromMnemonic } from "./recovery-key";export interface LocalUser {id: number;@@ -415,39 +421,48 @@ const TwoFactorRecoveryResponse = z.object({secretDecryptionNonce: z.string(),});-export type TwoFactorRecoveryResponse = z.infer<- typeof TwoFactorRecoveryResponse->;+export interface TwoFactorRecovery {+ client: AccountsClient;+ response: z.infer<typeof TwoFactorRecoveryResponse>;+}export const getRecoverTwoFactor = async (twoFactorType: TwoFactorType,sessionID: string,-): Promise<TwoFactorRecoveryResponse> => {- const res = await fetch(- await apiURL("/users/two-factor/recover", { twoFactorType, sessionID }),- { headers: publicRequestHeaders() },+): Promise<TwoFactorRecovery> => {+ const client = await getAccountsClient();+ const response = TwoFactorRecoveryResponse.parse(+ await getTwoFactorRecovery(client, twoFactorType, sessionID),);- ensureOk(res);- return TwoFactorRecoveryResponse.parse(await res.json());+ if (client !== (await getAccountsClient())) {+ throw namedError("session_expired", "Server endpoint changed");+ }+ return { client, response };};export const recoverTwoFactorFinish = async (twoFactorType: TwoFactorType,sessionID: string,- recoveryResponse: TwoFactorRecoveryResponse,+ recovery: TwoFactorRecovery,recoveryKeyMnemonic: string,) => {- const { encryptedSecret: encryptedData, secretDecryptionNonce: nonce } =- recoveryResponse;- const twoFactorSecret = await decryptBox(- { encryptedData, nonce },- await recoveryKeyFromMnemonic(recoveryKeyMnemonic),- );- const { id, keyAttributes, encryptedToken } = await removeTwoFactor(- twoFactorType,- sessionID,- twoFactorSecret,- );+ const { client, response } = recovery;+ if (client !== (await getAccountsClient())) {+ throw namedError("session_expired", "Server endpoint changed");+ }+ const { id, keyAttributes, encryptedToken } =+ TwoFactorAuthorizationResponse.parse(+ await recoverTwoFactor(+ client,+ twoFactorType,+ sessionID,+ response,+ recoveryKeyMnemonic,+ ),+ );+ if (client !== (await getAccountsClient())) {+ throw namedError("session_expired", "Server endpoint changed");+ }await resetSavedLocalUserTokens(id, encryptedToken);updateSavedLocalUser({isTwoFactorEnabled: undefined,@@ -457,17 +472,3 @@ export const recoverTwoFactorFinish = async (if (twoFactorType == "passkey") clearInflightPasskeySessionID();saveKeyAttributes(keyAttributes);};--const removeTwoFactor = async (- twoFactorType: TwoFactorType,- sessionID: string,- secret: string,-): Promise<TwoFactorAuthorizationResponse> => {- const res = await fetch(await apiURL("/users/two-factor/remove"), {- method: "POST",- headers: publicRequestHeaders(),- body: JSON.stringify({ twoFactorType, sessionID, secret }),- });- ensureOk(res);- return TwoFactorAuthorizationResponse.parse(await res.json());-};diff --git a/web/packages/wasm/prelogin/index.ts b/web/packages/wasm/prelogin/index.tsindex f29bb45dce..07711cb470 100644--- a/web/packages/wasm/prelogin/index.ts+++ b/web/packages/wasm/prelogin/index.ts@@ -1,8 +1,15 @@-import type { SrpSession } from "./pkg/ente_prelogin_wasm";+import type {+ AccountsClient,+ AccountsClientConfig,+ SrpSession,+} from "./pkg/ente_prelogin_wasm";export type EncryptedBoxB64 = Awaited<ReturnType<typeof encryptBox>>;export type KeyPair = Awaited<ReturnType<typeof generateKeyPair>>;-export type { GeneratedKek as DerivedKey } from "./pkg/ente_prelogin_wasm";+export type {+ AccountsClient,+ GeneratedKek as DerivedKey,+} from "./pkg/ente_prelogin_wasm";const wasm = () => import("./pkg/ente_prelogin_wasm");@@ -33,6 +40,34 @@ export const deriveSRPLoginKey = async (kekB64: string) =>export const generateSRPSetup = async (kekB64: string, srpUserID: string) =>(await wasm()).authGenerateSrpSetup(kekB64, srpUserID);+export const createAccountsClient = async (config: AccountsClientConfig) =>+ (await wasm()).createAccountsClient(config);++export const getTwoFactorRecovery = async (+ client: AccountsClient,+ twoFactorType: "totp" | "passkey",+ sessionID: string,+): Promise<unknown> =>+ (await wasm()).getTwoFactorRecovery(client, twoFactorType, sessionID);++export const recoverTwoFactor = async (+ client: AccountsClient,+ twoFactorType: "totp" | "passkey",+ sessionID: string,+ recoveryResponse: {+ encryptedSecret: string;+ secretDecryptionNonce: string;+ },+ recoveryKey: string,+): Promise<unknown> =>+ (await wasm()).recoverTwoFactor(+ client,+ twoFactorType,+ sessionID,+ recoveryResponse,+ recoveryKey,+ );+export const recoveryKeyFromMnemonicOrHex = async (value: string) =>(await wasm()).authRecoveryKeyFromMnemonicOrHex(value);diff --git a/web/packages/wasm/prelogin/tests/auth.test.ts b/web/packages/wasm/prelogin/tests/auth.test.tsindex 3d911cc6ef..f918b33c23 100644--- a/web/packages/wasm/prelogin/tests/auth.test.ts+++ b/web/packages/wasm/prelogin/tests/auth.test.ts@@ -1,5 +1,12 @@-import { expect, test } from "vitest";-import { deriveKey } from "../index";+import { expect, test, vi } from "vitest";+import {+ createAccountsClient,+ deriveKey,+ encryptBox,+ getTwoFactorRecovery,+ recoverTwoFactor,+ recoveryKeyToMnemonic,+} from "../index";import {authDeriveSrpLoginKey,authGenerateInteractiveKek,@@ -40,3 +47,113 @@ test("generates SRP setup attributes from a kek", () => {0,);});++test("recovers TOTP and passkey through Rust with the existing wire format", async () => {+ const recoveryKey = cryptoGenerateKey();+ const recoveryKeyHex = Buffer.from(recoveryKey, "base64").toString("hex");+ const authorization = {+ id: 123,+ encryptedToken: "sealed-token",+ keyAttributes: {+ kekSalt: "salt",+ encryptedKey: "key",+ keyDecryptionNonce: "nonce",+ publicKey: "public-key",+ encryptedSecretKey: "private-key",+ secretKeyDecryptionNonce: "private-key-nonce",+ memLimit: 67_108_864,+ opsLimit: 2,+ },+ };+ const factors = [+ ["totp", "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"],+ ["passkey", cryptoGenerateKey()],+ ] as const;+ try {+ for (const [factor, secret] of factors) {+ const clientVersion = factor == "totp" ? undefined : "test";+ const client = await createAccountsClient({+ origin: "http://localhost",+ clientPackage: "io.ente.auth.web",+ ...(clientVersion && { clientVersion }),+ });+ const encrypted = await encryptBox(secret, recoveryKey);+ const envelope = {+ encryptedSecret: encrypted.encryptedData,+ secretDecryptionNonce: encrypted.nonce,+ };+ let status = 200;+ const fetch = vi.fn(async (request: Request) => {+ const url = new URL(request.url);+ expect(url.origin).toBe("http://localhost");+ expect(request.headers.get("X-Client-Package")).toBe(+ "io.ente.auth.web",+ );+ expect(request.headers.get("X-Client-Version")).toBe(+ clientVersion ?? null,+ );+ expect(request.headers.get("X-Auth-Token")).toBeNull();+ if (request.method == "GET") {+ expect(url.pathname).toBe("/users/two-factor/recover");+ expect(Object.fromEntries(url.searchParams)).toStrictEqual({+ sessionID: "recovery-session",+ twoFactorType: factor,+ });+ } else {+ expect(request.method).toBe("POST");+ expect(url.pathname).toBe("/users/two-factor/remove");+ expect(await request.json()).toStrictEqual({+ sessionId: "recovery-session",+ twoFactorType: factor,+ secret,+ });+ }+ const response = Response.json(+ request.method == "GET" ? envelope : authorization,+ { status },+ );+ Object.defineProperty(response, "url", { value: request.url });+ return response;+ });+ vi.stubGlobal("fetch", fetch);+ const get = () =>+ getTwoFactorRecovery(client, factor, "recovery-session");+ expect(await get()).toStrictEqual(envelope);+ const recover = (key: string) =>+ recoverTwoFactor(+ client,+ factor,+ "recovery-session",+ envelope,+ key,+ );+ await expect(recover("ff".repeat(32))).rejects.toMatchObject({+ name: "incorrect_recovery_key",+ });+ expect(fetch).toHaveBeenCalledTimes(1);+ const key =+ factor == "totp"+ ? recoveryKeyHex+ : await recoveryKeyToMnemonic(recoveryKey);+ await expect(recover(key)).resolves.toStrictEqual(authorization);+ expect(fetch).toHaveBeenCalledTimes(2);+ status = 404;+ await expect(get()).rejects.toMatchObject({+ name: "session_expired",+ status,+ });+ status = 403;+ await expect(get()).rejects.toMatchObject({+ name: "Error",+ status,+ });+ status = 500;+ const calls = fetch.mock.calls.length;+ await expect(recover(key)).rejects.toMatchObject({ status });+ expect(fetch).toHaveBeenCalledTimes(calls + 1);+ client.free();+ }+ } finally {+ vi.unstubAllGlobals();+ }+});