Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Improve unparseable Auth code handling

Neeraj Gupta6543ab366855
diff --git a/mobile/apps/auth/lib/l10n/arb/app_en.arb b/mobile/apps/auth/lib/l10n/arb/app_en.arb
index 5c2a7bd970..5bdc22f057 100644
--- a/mobile/apps/auth/lib/l10n/arb/app_en.arb
+++ b/mobile/apps/auth/lib/l10n/arb/app_en.arb
@@ -486,6 +486,9 @@
"somethingWentWrongParsingCode": "We were unable to parse {x} codes.",
"updateNotAvailable": "Update not available",
"viewRawCodes": "View raw codes",
+ "parsingError": "Parsing error",
+ "deleteUnparseableCodeTitle": "Delete unparseable code?",
+ "deleteUnparseableCodeMessage": "This will permanently delete this code from Auth. It will not be moved to trash.",
"rawCodes": "Raw codes",
"rawCodeData": "Raw code data",
"appLock": "App lock",
diff --git a/mobile/apps/auth/lib/models/code_parse_error.dart b/mobile/apps/auth/lib/models/code_parse_error.dart
new file mode 100644
index 0000000000..6eccaa62d2
--- /dev/null
+++ b/mobile/apps/auth/lib/models/code_parse_error.dart
@@ -0,0 +1,107 @@
+import 'dart:convert';
+
+const Set<String> _supportedOtpHosts = {'totp', 'hotp', 'steam'};
+
+class CodeParseError implements Exception {
+ const CodeParseError._(this.message);
+
+ final String message;
+
+ factory CodeParseError.from({
+ required Object error,
+ required String storedRawData,
+ }) {
+ return CodeParseError._(_rootCause(error, storedRawData));
+ }
+
+ @override
+ String toString() => message;
+}
+
+String _rootCause(Object error, String storedRawData) {
+ final decodedStoredData = _tryDecodeJson(storedRawData);
+
+ if (decodedStoredData is String) {
+ return _rootCauseFromOtpUrl(error, decodedStoredData) ??
+ 'OTP URL could not be parsed';
+ }
+ if (decodedStoredData is Map) {
+ final rawData = decodedStoredData['rawData'];
+ if (rawData is! String || rawData.isEmpty) {
+ return 'Stored code export is missing rawData';
+ }
+ final otpUrlRootCause = _rootCauseFromOtpUrl(error, rawData);
+ if (otpUrlRootCause != null) {
+ return otpUrlRootCause;
+ }
+ if (decodedStoredData['display'] != null) {
+ return 'Code display metadata is invalid';
+ }
+ return 'Stored code data could not be parsed';
+ }
+
+ if (error is FormatException) {
+ return 'Stored code data is not valid JSON';
+ }
+ return 'Stored code data is not a supported format';
+}
+
+String? _rootCauseFromOtpUrl(Object error, String rawData) {
+ if (!rawData.startsWith('otpauth://')) {
+ return 'Stored code data is not an OTP URL';
+ }
+
+ final uri = Uri.tryParse(rawData);
+ if (uri == null) {
+ return 'OTP URL is malformed';
+ }
+ if (!_supportedOtpHosts.contains(uri.host)) {
+ // This message is shown in UI and logged, so keep it limited to Uri.host.
+ // The raw path/query can contain labels, issuers, or OTP secrets.
+ final host = uri.host.isEmpty ? 'unknown' : uri.host;
+ return 'Unsupported OTP type: $host';
+ }
+ final queryParameters = _tryGetQueryParameters(uri);
+ if (queryParameters == null) {
+ return 'OTP URL is malformed';
+ }
+ if ((queryParameters['secret'] ?? '').isEmpty) {
+ return 'OTP URL is missing a secret';
+ }
+ if (_hasInvalidCodeDisplay(queryParameters)) {
+ return 'Code display metadata is invalid';
+ }
+ if (error is FormatException) {
+ return 'OTP URL is malformed';
+ }
+ return null;
+}
+
+bool _hasInvalidCodeDisplay(Map<String, String> queryParameters) {
+ final codeDisplay = queryParameters['codeDisplay'];
+ if (codeDisplay == null) {
+ return false;
+ }
+ try {
+ jsonDecode(codeDisplay.replaceAll('%2C', ','));
+ return false;
+ } catch (_) {
+ return true;
+ }
+}
+
+Map<String, String>? _tryGetQueryParameters(Uri uri) {
+ try {
+ return uri.queryParameters;
+ } catch (_) {
+ return null;
+ }
+}
+
+Object? _tryDecodeJson(String value) {
+ try {
+ return jsonDecode(value);
+ } catch (_) {
+ return null;
+ }
+}
diff --git a/mobile/apps/auth/lib/store/code_store.dart b/mobile/apps/auth/lib/store/code_store.dart
index d6f8b2b673..76e8a72e14 100644
--- a/mobile/apps/auth/lib/store/code_store.dart
+++ b/mobile/apps/auth/lib/store/code_store.dart
@@ -6,6 +6,7 @@ import 'package:ente_auth/core/configuration.dart';
import 'package:ente_auth/events/codes_updated_event.dart';
import 'package:ente_auth/models/authenticator/entity_result.dart';
import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/models/code_parse_error.dart';
import 'package:ente_auth/services/authenticator_service.dart';
import 'package:ente_auth/store/offline_authenticator_db.dart';
import 'package:ente_events/event_bus.dart';
@@ -87,8 +88,12 @@ class CodeStore {
code = Code.fromExportJson(decodeJson);
}
} catch (e, s) {
- code = Code.withError(e, entity.rawData);
- _logger.severe("Could not parse code", e, s);
+ final parseError = CodeParseError.from(
+ error: e,
+ storedRawData: entity.rawData,
+ );
+ code = Code.withError(parseError, entity.rawData);
+ _logger.severe("Could not parse code: $parseError", e, s);
}
code.generatedID = entity.generatedID;
code.hasSynced = entity.hasSynced;
diff --git a/mobile/apps/auth/lib/ui/code_error_widget.dart b/mobile/apps/auth/lib/ui/code_error_widget.dart
index 91ea65adfd..2514126648 100644
--- a/mobile/apps/auth/lib/ui/code_error_widget.dart
+++ b/mobile/apps/auth/lib/ui/code_error_widget.dart
@@ -86,9 +86,7 @@ class CodeErrorWidget extends StatelessWidget {
await showDialog(
context: context,
builder: (BuildContext context) {
- return RawCodesViewer(
- errors.map((e) => e.rawData).join('\n'),
- );
+ return RawCodesViewer(errors);
},
barrierColor: Colors.black87,
barrierDismissible: false,
diff --git a/mobile/apps/auth/lib/ui/tools/debug/raw_codes_viewer.dart b/mobile/apps/auth/lib/ui/tools/debug/raw_codes_viewer.dart
index e69936de37..357f6c2225 100644
--- a/mobile/apps/auth/lib/ui/tools/debug/raw_codes_viewer.dart
+++ b/mobile/apps/auth/lib/ui/tools/debug/raw_codes_viewer.dart
@@ -1,16 +1,37 @@
+import 'dart:async';
+
+import 'package:ente_auth/ente_theme_data.dart';
import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/services/local_backup_service.dart';
+import 'package:ente_auth/store/code_store.dart';
+import 'package:ente_auth/theme/ente_theme.dart';
+import 'package:ente_auth/ui/components/buttons/button_widget.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/platform_util.dart';
+import 'package:ente_lock_screen/local_authentication_service.dart';
import 'package:flutter/material.dart';
+import 'package:logging/logging.dart';
class RawCodesViewer extends StatefulWidget {
- final String rawData;
- const RawCodesViewer(this.rawData, {super.key});
+ final List<Code> errors;
+
+ const RawCodesViewer(this.errors, {super.key});
@override
State<RawCodesViewer> createState() => _RawCodesViewerState();
}
class _RawCodesViewerState extends State<RawCodesViewer> {
+ final Logger _logger = Logger('RawCodesViewer');
+ late final List<Code> _errors;
+
+ @override
+ void initState() {
+ super.initState();
+ _errors = List.of(widget.errors);
+ }
+
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -20,20 +41,143 @@ class _RawCodesViewerState extends State<RawCodesViewer> {
}
Widget _getBody() {
+ if (_errors.isEmpty) {
+ return Center(child: Text(context.l10n.noResult));
+ }
+
+ return ListView.separated(
+ padding: const EdgeInsets.all(12),
+ itemCount: _errors.length,
+ separatorBuilder: (_, __) => const SizedBox(height: 12),
+ itemBuilder: (context, index) {
+ return _RawCodeCard(
+ code: _errors[index],
+ index: index,
+ onDelete: _errors[index].generatedID == null
+ ? null
+ : () => _confirmDelete(_errors[index]),
+ );
+ },
+ );
+ }
+
+ Future<void> _confirmDelete(Code code) async {
+ FocusScope.of(context).requestFocus();
+ final l10n = context.l10n;
+ final result = await showChoiceActionSheet(
+ context,
+ title: l10n.deleteUnparseableCodeTitle,
+ body: l10n.deleteUnparseableCodeMessage,
+ firstButtonLabel: l10n.delete,
+ isCritical: true,
+ );
+ if (result?.action != ButtonAction.first || !mounted) {
+ return;
+ }
+ final isAuthSuccessful = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(context, l10n.deleteCodeAuthMessage);
+ if (!isAuthSuccessful) {
+ return;
+ }
+ await _deleteCode(code);
+ }
+
+ Future<void> _deleteCode(Code code) async {
+ try {
+ await CodeStore.instance.removeCode(code);
+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _errors.removeWhere((error) => error.generatedID == code.generatedID);
+ });
+ } catch (e, s) {
+ _logger.severe('Failed to delete unparseable code', e, s);
+ if (mounted) {
+ showGenericErrorDialog(context: context, error: e).ignore();
+ }
+ }
+ }
+}
+
+class _RawCodeCard extends StatelessWidget {
+ const _RawCodeCard({
+ required this.code,
+ required this.index,
+ required this.onDelete,
+ });
+
+ final Code code;
+ final int index;
+ final VoidCallback? onDelete;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final parseError = code.err?.toString();
+
return Container(
- padding: const EdgeInsets.only(left: 12, top: 8, right: 12),
- child: SingleChildScrollView(
- child: SelectableRegion(
- focusNode: FocusNode(),
- selectionControls: PlatformUtil.selectionControls,
- child: Text(
- widget.rawData,
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.codeCardBackgroundColor,
+ borderRadius: BorderRadius.circular(8),
+ ),
+ padding: const EdgeInsets.fromLTRB(12, 10, 8, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ '${context.l10n.rawCodeData} ${index + 1}',
+ style: const TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ IconButton(
+ tooltip: context.l10n.delete,
+ visualDensity: VisualDensity.compact,
+ color: colorScheme.warning700,
+ onPressed: onDelete,
+ icon: const Icon(Icons.delete_outline, size: 20),
+ ),
+ ],
+ ),
+ if (parseError != null && parseError.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(
+ context.l10n.parsingError,
+ style: TextStyle(
+ color: colorScheme.warning700,
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 4),
+ SelectableText(
+ parseError,
+ selectionControls: PlatformUtil.selectionControls,
+ style: TextStyle(
+ color: colorScheme.warning700,
+ fontSize: 12,
+ height: 1.2,
+ ),
+ ),
+ ],
+ const SizedBox(height: 6),
+ SelectableText(
+ code.rawData,
+ selectionControls: PlatformUtil.selectionControls,
style: const TextStyle(
fontFeatures: [FontFeature.tabularFigures()],
height: 1.2,
+ fontSize: 13,
),
),
- ),
+ ],
),
);
}