yubioath-flutter/lib/oath/views/add_account_page.dart

597 lines
22 KiB
Dart
Raw Normal View History

2022-10-04 13:12:54 +03:00
/*
* Copyright (C) 2022 Yubico.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2022-09-13 13:55:17 +03:00
import 'dart:async';
2022-03-22 17:16:52 +03:00
import 'dart:convert';
2022-09-14 16:54:51 +03:00
import 'dart:io';
2022-04-14 10:08:33 +03:00
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
2022-09-05 16:10:44 +03:00
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
2022-09-14 10:48:37 +03:00
import '../../android/oath/state.dart';
import '../../app/logging.dart';
2022-03-25 17:43:32 +03:00
import '../../app/message.dart';
import '../../app/models.dart';
2022-04-14 10:08:33 +03:00
import '../../app/state.dart';
2022-09-13 13:55:17 +03:00
import '../../app/views/user_interaction.dart';
import '../../cancellation_exception.dart';
import '../../core/state.dart';
2022-06-13 17:45:26 +03:00
import '../../desktop/models.dart';
2022-09-13 13:55:17 +03:00
import '../../management/models.dart';
2022-09-01 11:14:59 +03:00
import '../../widgets/choice_filter_chip.dart';
2022-03-23 12:46:35 +03:00
import '../../widgets/file_drop_target.dart';
import '../../widgets/responsive_dialog.dart';
2022-07-06 16:22:15 +03:00
import '../../widgets/utf8_utils.dart';
2022-09-12 13:58:17 +03:00
import '../keys.dart' as keys;
2022-03-15 20:04:26 +03:00
import '../models.dart';
2021-12-02 16:20:05 +03:00
import '../state.dart';
2022-09-14 14:19:39 +03:00
import 'unlock_form.dart';
import 'utils.dart';
final _log = Logger('oath.view.add_account_page');
final _secretFormatterPattern =
RegExp('[abcdefghijklmnopqrstuvwxyz234567 ]', caseSensitive: false);
enum _QrScanState { none, scanning, success, failed }
2022-03-15 20:04:26 +03:00
class OathAddAccountPage extends ConsumerStatefulWidget {
2022-09-13 13:55:17 +03:00
final DevicePath? devicePath;
final OathState? state;
final List<OathCredential>? credentials;
final CredentialData? credentialData;
const OathAddAccountPage(
this.devicePath,
this.state, {
super.key,
required this.credentials,
this.credentialData,
});
2021-12-02 16:20:05 +03:00
@override
2022-03-15 20:04:26 +03:00
ConsumerState<ConsumerStatefulWidget> createState() =>
_OathAddAccountPageState();
2021-12-02 16:20:05 +03:00
}
2022-03-15 20:04:26 +03:00
class _OathAddAccountPageState extends ConsumerState<OathAddAccountPage> {
final _issuerController = TextEditingController();
final _accountController = TextEditingController();
final _secretController = TextEditingController();
final _periodController = TextEditingController(text: '$defaultPeriod');
2022-09-13 13:55:17 +03:00
UserInteractionController? _promptController;
Uri? _otpauthUri;
2021-12-02 16:20:05 +03:00
bool _touch = false;
OathType _oathType = defaultOathType;
HashAlgorithm _hashAlgorithm = defaultHashAlgorithm;
int _digits = defaultDigits;
bool _validateSecretLength = false;
_QrScanState _qrState = _QrScanState.none;
bool _isObscure = true;
List<int> _periodValues = [20, 30, 45, 60];
List<int> _digitsValues = [6, 8];
List<OathCredential>? _credentials;
@override
void dispose() {
_issuerController.dispose();
_accountController.dispose();
_secretController.dispose();
_periodController.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
final cred = widget.credentialData;
if (cred != null) {
_loadCredentialData(cred);
}
}
_scanQrCode(QrScanner qrScanner) async {
try {
setState(() {
// If we have a previous scan result stored, clear it
if (_qrState == _QrScanState.success) {
_issuerController.text = '';
_accountController.text = '';
_secretController.text = '';
_oathType = defaultOathType;
_hashAlgorithm = defaultHashAlgorithm;
_periodController.text = '$defaultPeriod';
_digits = defaultDigits;
}
_qrState = _QrScanState.scanning;
});
2022-03-29 14:57:08 +03:00
final otpauth = await qrScanner.scanQr();
2022-06-13 17:45:26 +03:00
if (otpauth == null) {
if (!mounted) return;
2022-09-05 16:10:44 +03:00
showMessage(context, AppLocalizations.of(context)!.oath_no_qr_code);
2022-06-13 17:45:26 +03:00
setState(() {
_qrState = _QrScanState.failed;
});
} else {
final data = CredentialData.fromUri(Uri.parse(otpauth));
_loadCredentialData(data);
}
} catch (e) {
2022-06-13 17:45:26 +03:00
final String errorMessage;
// TODO: Make this cleaner than importing desktop specific RpcError.
if (e is RpcError) {
errorMessage = e.message;
} else {
errorMessage = e.toString();
}
if (e is! CancellationException) {
showMessage(
context,
'${AppLocalizations.of(context)!.oath_failed_reading_qr}: $errorMessage',
duration: const Duration(seconds: 4),
);
}
setState(() {
_qrState = _QrScanState.failed;
});
}
}
_loadCredentialData(CredentialData data) {
setState(() {
_issuerController.text = data.issuer?.trim() ?? '';
_accountController.text = data.name.trim();
_secretController.text = data.secret;
_oathType = data.oathType;
_hashAlgorithm = data.hashAlgorithm;
_periodValues = [data.period];
_periodController.text = '${data.period}';
_digitsValues = [data.digits];
_digits = data.digits;
_isObscure = true;
_qrState = _QrScanState.success;
});
}
2022-09-14 10:48:37 +03:00
Future<void> _doAddCredential(
{DevicePath? devicePath, required Uri credUri}) async {
2022-09-13 13:55:17 +03:00
try {
2022-09-14 10:48:37 +03:00
if (devicePath == null) {
2022-09-14 16:54:51 +03:00
assert(Platform.isAndroid, 'devicePath is only optional for Android');
2022-09-14 10:48:37 +03:00
await ref
.read(addCredentialToAnyProvider)
.call(credUri, requireTouch: _touch);
} else {
await ref
.read(credentialListProvider(devicePath).notifier)
.addAccount(credUri, requireTouch: _touch);
}
if (!mounted) return;
Navigator.of(context).pop();
showMessage(
context, AppLocalizations.of(context)!.oath_success_add_account);
2022-09-13 13:55:17 +03:00
} on CancellationException catch (_) {
// ignored
} catch (e) {
_log.error('Failed to add account', e);
final String errorMessage;
// TODO: Make this cleaner than importing desktop specific RpcError.
if (e is RpcError) {
errorMessage = e.message;
} else {
errorMessage = e.toString();
}
showMessage(
context,
'${AppLocalizations.of(context)!.oath_fail_add_account}: $errorMessage',
duration: const Duration(seconds: 4),
);
}
}
@override
2021-12-02 16:20:05 +03:00
Widget build(BuildContext context) {
2022-09-13 13:55:17 +03:00
final deviceNode = ref.watch(currentDeviceProvider);
if (widget.devicePath != null && widget.devicePath != deviceNode?.path) {
// If the dialog was started for a specific device and it was
// changed/removed, close the dialog.
Navigator.of(context).popUntil((route) => route.isFirst);
}
final OathState? oathState;
if (widget.state == null && deviceNode != null) {
oathState = ref
.watch(oathStateProvider(deviceNode.path))
.maybeWhen(data: (data) => data, orElse: () => null);
_credentials = ref
.watch(credentialListProvider(deviceNode.path))
?.map((e) => e.credential)
.toList();
2022-09-13 13:55:17 +03:00
} else {
oathState = widget.state;
_credentials = widget.credentials;
2022-09-13 13:55:17 +03:00
}
final otpauthUri = _otpauthUri;
_promptController?.updateContent(title: 'Insert YubiKey');
if (otpauthUri != null && deviceNode != null) {
final deviceData = ref.watch(currentDeviceDataProvider);
deviceData.when(data: (data) {
if (Capability.oath.value ^
(data.info.config.enabledCapabilities[deviceNode.transport] ??
0) !=
0) {
if (oathState == null) {
_promptController?.updateContent(title: 'Please wait...');
} else if (oathState.locked) {
2022-09-14 16:54:51 +03:00
_promptController?.close();
2022-09-13 13:55:17 +03:00
} else {
_otpauthUri = null;
_promptController?.close();
2022-09-14 10:48:37 +03:00
Timer.run(() => _doAddCredential(
2022-09-14 16:54:51 +03:00
devicePath: deviceNode.path,
credUri: otpauthUri,
));
2022-09-13 13:55:17 +03:00
}
} else {
_promptController?.updateContent(title: 'Unsupported YubiKey');
}
}, error: (error, _) {
_promptController?.updateContent(title: 'Unsupported YubiKey');
}, loading: () {
_promptController?.updateContent(title: 'Please wait...');
});
}
final period = int.tryParse(_periodController.text) ?? -1;
final remaining = getRemainingKeySpace(
oathType: _oathType,
period: period,
issuer: _issuerController.text.trim(),
name: _accountController.text.trim(),
);
final issuerRemaining = remaining.first;
final nameRemaining = remaining.second;
final secret = _secretController.text.replaceAll(' ', '');
final secretLengthValid = secret.length * 5 % 8 < 5;
// is this credentials name/issuer pair different from all other?
final isUnique = _credentials
?.where((element) =>
element.name == _accountController.text.trim() &&
(element.issuer ?? '') == _issuerController.text.trim())
.isEmpty ??
true;
2022-10-21 11:31:40 +03:00
final issuerNoColon = !_issuerController.text.contains(':');
2022-09-14 14:19:39 +03:00
final isLocked = oathState?.locked ?? false;
final isValid = !isLocked &&
_accountController.text.trim().isNotEmpty &&
secret.isNotEmpty &&
isUnique &&
2022-10-21 11:31:40 +03:00
issuerNoColon &&
issuerRemaining >= -1 &&
nameRemaining >= 0 &&
period > 0;
final qrScanner = ref.watch(qrScannerProvider);
2022-09-14 14:19:39 +03:00
final hashAlgorithms = HashAlgorithm.values
.where((alg) =>
alg != HashAlgorithm.sha512 ||
(oathState?.version.isAtLeast(4, 3, 1) ?? true))
.toList();
2022-09-13 13:55:17 +03:00
if (!hashAlgorithms.contains(_hashAlgorithm)) {
_hashAlgorithm = HashAlgorithm.sha1;
}
2022-09-14 14:19:39 +03:00
if (!(oathState?.version.isAtLeast(4, 2) ?? true)) {
// Touch not supported
_touch = false;
}
void submit() async {
if (secretLengthValid) {
final issuer = _issuerController.text.trim();
final cred = CredentialData(
issuer: issuer.isEmpty ? null : issuer,
name: _accountController.text.trim(),
secret: secret,
oathType: _oathType,
hashAlgorithm: _hashAlgorithm,
digits: _digits,
period: period,
);
2022-09-13 13:55:17 +03:00
final devicePath = deviceNode?.path;
if (devicePath != null) {
2022-09-14 10:48:37 +03:00
await _doAddCredential(devicePath: devicePath, credUri: cred.toUri());
2022-09-14 16:54:51 +03:00
} else if (Platform.isAndroid) {
2022-09-14 10:48:37 +03:00
// Send the credential to Android to be added to the next YubiKey
await _doAddCredential(devicePath: null, credUri: cred.toUri());
2022-09-13 13:55:17 +03:00
} else {
2022-09-14 10:48:37 +03:00
// Desktop. No YubiKey, prompt and store the cred.
2022-09-13 13:55:17 +03:00
_otpauthUri = cred.toUri();
_promptController = promptUserInteraction(
2022-06-13 17:45:26 +03:00
context,
2022-09-13 13:55:17 +03:00
title: 'Insert YubiKey',
description: 'Add account',
icon: const Icon(Icons.usb),
onCancel: () {
_otpauthUri = null;
},
2022-06-13 17:45:26 +03:00
);
}
} else {
setState(() {
_validateSecretLength = true;
});
}
}
2022-03-15 20:04:26 +03:00
return ResponsiveDialog(
2022-09-05 16:10:44 +03:00
title: Text(AppLocalizations.of(context)!.oath_add_account),
2022-05-12 09:34:51 +03:00
actions: [
TextButton(
onPressed: isValid ? submit : null,
2022-09-05 16:10:44 +03:00
child: Text(AppLocalizations.of(context)!.oath_save,
2022-09-12 13:58:17 +03:00
key: keys.saveButton),
2022-05-12 09:34:51 +03:00
),
],
2022-03-23 12:46:35 +03:00
child: FileDropTarget(
onFileDropped: (fileData) async {
if (qrScanner != null) {
final b64Image = base64Encode(fileData);
final otpauth = await qrScanner.scanQr(b64Image);
2022-06-13 17:45:26 +03:00
if (otpauth == null) {
if (!mounted) return;
2022-09-05 16:10:44 +03:00
showMessage(
context, AppLocalizations.of(context)!.oath_no_qr_code);
2022-06-13 17:45:26 +03:00
} else {
final data = CredentialData.fromUri(Uri.parse(otpauth));
_loadCredentialData(data);
}
2022-03-23 12:46:35 +03:00
}
},
2022-09-14 16:54:51 +03:00
child: isLocked
? Padding(
padding: const EdgeInsets.symmetric(vertical: 18),
child:
UnlockForm(deviceNode!.path, keystore: oathState!.keystore),
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0),
child: Column(
2022-09-14 14:19:39 +03:00
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: keys.issuerField,
controller: _issuerController,
autofocus: widget.credentialData == null,
2022-09-14 14:19:39 +03:00
enabled: issuerRemaining > 0,
maxLength: max(issuerRemaining, 1),
2022-10-21 11:31:40 +03:00
inputFormatters: [
limitBytesLength(issuerRemaining),
],
2022-09-14 14:19:39 +03:00
buildCounter:
buildByteCounterFor(_issuerController.text.trim()),
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText:
AppLocalizations.of(context)!.oath_issuer_optional,
helperText:
'', // Prevents dialog resizing when disabled
prefixIcon: const Icon(Icons.business_outlined),
2022-10-21 11:31:40 +03:00
errorText: issuerNoColon
? null
: AppLocalizations.of(context)!
.oath_invalid_character_issuer,
),
2022-09-14 14:19:39 +03:00
textInputAction: TextInputAction.next,
onChanged: (value) {
setState(() {
2022-09-14 14:19:39 +03:00
// Update maxlengths
});
},
2022-09-14 14:19:39 +03:00
onSubmitted: (_) {
if (isValid) submit();
},
2022-04-04 13:09:34 +03:00
),
2022-09-14 14:19:39 +03:00
TextField(
key: keys.nameField,
controller: _accountController,
maxLength: max(nameRemaining, 1),
buildCounter:
buildByteCounterFor(_accountController.text.trim()),
inputFormatters: [limitBytesLength(nameRemaining)],
decoration: InputDecoration(
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.person_outline),
labelText:
AppLocalizations.of(context)!.oath_account_name,
helperText:
'', // Prevents dialog resizing when disabled
errorText: isUnique
? null
: AppLocalizations.of(context)!.oath_duplicate_name,
),
textInputAction: TextInputAction.next,
onChanged: (value) {
setState(() {
// Update maxlengths
});
},
onSubmitted: (_) {
if (isValid) submit();
},
),
TextField(
key: keys.secretField,
controller: _secretController,
obscureText: _isObscure,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
_secretFormatterPattern)
],
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
color: IconTheme.of(context).color,
),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
},
),
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.key_outlined),
labelText:
AppLocalizations.of(context)!.oath_secret_key,
errorText: _validateSecretLength && !secretLengthValid
? AppLocalizations.of(context)!
.oath_invalid_length
: null),
readOnly: _qrState == _QrScanState.success,
textInputAction: TextInputAction.done,
onChanged: (value) {
setState(() {
2022-09-14 14:19:39 +03:00
_validateSecretLength = false;
});
},
2022-09-14 14:19:39 +03:00
onSubmitted: (_) {
if (isValid) submit();
},
),
if (isDesktop && qrScanner != null)
2022-09-14 14:19:39 +03:00
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: ActionChip(
avatar: _qrState != _QrScanState.scanning
? (_qrState == _QrScanState.success
? const Icon(Icons.qr_code)
: const Icon(
Icons.qr_code_scanner_outlined))
: const CircularProgressIndicator(
strokeWidth: 2.0),
label: _qrState == _QrScanState.success
? Text(AppLocalizations.of(context)!
.oath_scanned_qr)
: Text(
AppLocalizations.of(context)!.oath_scan_qr),
onPressed: () {
_scanQrCode(qrScanner);
}),
),
const Divider(),
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4.0,
runSpacing: 8.0,
children: [
if (oathState?.version.isAtLeast(4, 2) ?? true)
FilterChip(
label: Text(AppLocalizations.of(context)!
.oath_require_touch),
selected: _touch,
onSelected: (value) {
setState(() {
2022-09-14 14:19:39 +03:00
_touch = value;
});
2022-09-14 14:19:39 +03:00
},
),
ChoiceFilterChip<OathType>(
items: OathType.values,
value: _oathType,
selected: _oathType != defaultOathType,
itemBuilder: (value) => Text(value.displayName),
onChanged: _qrState != _QrScanState.success
? (value) {
setState(() {
_oathType = value;
});
}
: null,
),
ChoiceFilterChip<HashAlgorithm>(
items: hashAlgorithms,
value: _hashAlgorithm,
selected: _hashAlgorithm != defaultHashAlgorithm,
itemBuilder: (value) => Text(value.displayName),
onChanged: _qrState != _QrScanState.success
? (value) {
setState(() {
_hashAlgorithm = value;
});
}
: null,
),
if (_oathType == OathType.totp)
ChoiceFilterChip<int>(
items: _periodValues,
value: int.tryParse(_periodController.text) ??
defaultPeriod,
selected: int.tryParse(_periodController.text) !=
defaultPeriod,
itemBuilder: ((value) => Text(
'$value ${AppLocalizations.of(context)!.oath_sec}')),
onChanged: _qrState != _QrScanState.success
? (period) {
setState(() {
_periodController.text = '$period';
});
}
: null,
),
ChoiceFilterChip<int>(
items: _digitsValues,
value: _digits,
selected: _digits != defaultDigits,
itemBuilder: (value) => Text(
'$value ${AppLocalizations.of(context)!.oath_digits}'),
onChanged: _qrState != _QrScanState.success
? (digits) {
setState(() {
_digits = digits;
});
}
: null,
),
],
),
2022-09-14 14:19:39 +03:00
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: e,
))
.toList(),
),
2022-09-14 16:54:51 +03:00
),
2022-03-23 12:46:35 +03:00
),
);
}
}