yubioath-flutter/lib/otp/views/configure_yubiotp_dialog.dart

434 lines
16 KiB
Dart
Raw Normal View History

2023-11-09 16:09:59 +03:00
/*
* Copyright (C) 2023 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.
*/
2023-11-17 15:02:51 +03:00
import 'dart:io';
2023-12-13 21:35:17 +03:00
import 'dart:math';
2023-11-09 16:09:59 +03:00
2023-11-17 15:02:51 +03:00
import 'package:file_picker/file_picker.dart';
2024-03-21 17:54:21 +03:00
import 'package:flutter/gestures.dart';
2023-11-09 16:09:59 +03:00
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
2024-03-08 11:30:47 +03:00
import 'package:material_symbols_icons/symbols.dart';
2024-03-21 17:54:21 +03:00
import 'package:url_launcher/url_launcher.dart';
2023-11-09 16:09:59 +03:00
2023-12-13 21:35:17 +03:00
import '../../app/logging.dart';
2023-11-09 16:09:59 +03:00
import '../../app/message.dart';
import '../../app/models.dart';
import '../../app/state.dart';
2023-12-13 21:35:17 +03:00
import '../../core/models.dart';
import '../../core/state.dart';
import '../../widgets/app_input_decoration.dart';
import '../../widgets/app_text_field.dart';
2023-12-13 21:35:17 +03:00
import '../../widgets/choice_filter_chip.dart';
2023-11-09 16:09:59 +03:00
import '../../widgets/responsive_dialog.dart';
2023-12-13 21:35:17 +03:00
import '../keys.dart' as keys;
2023-11-09 16:09:59 +03:00
import '../models.dart';
import '../state.dart';
2024-03-27 18:42:56 +03:00
import 'access_code_dialog.dart';
2023-11-09 16:09:59 +03:00
import 'overwrite_confirm_dialog.dart';
final _log = Logger('otp.view.configure_yubiotp_dialog');
2023-11-17 15:02:51 +03:00
enum OutputActions {
selectFile,
noOutput;
const OutputActions();
String getDisplayName(AppLocalizations l10n) => switch (this) {
2023-12-14 18:55:57 +03:00
OutputActions.selectFile => l10n.l_select_file,
OutputActions.noOutput => l10n.l_no_export_file
2023-11-17 15:02:51 +03:00
};
}
final uploadOtpUri = Uri.parse('https://upload.yubico.com');
2023-11-09 16:09:59 +03:00
class ConfigureYubiOtpDialog extends ConsumerStatefulWidget {
final DevicePath devicePath;
final OtpSlot otpSlot;
const ConfigureYubiOtpDialog(this.devicePath, this.otpSlot, {super.key});
@override
ConsumerState<ConsumerStatefulWidget> createState() =>
_ConfigureYubiOtpDialogState();
}
class _ConfigureYubiOtpDialogState
extends ConsumerState<ConfigureYubiOtpDialog> {
2023-11-17 15:02:51 +03:00
final _secretController = TextEditingController();
2023-11-09 16:09:59 +03:00
final _publicIdController = TextEditingController();
final _privateIdController = TextEditingController();
2023-11-23 18:25:11 +03:00
OutputActions _action = OutputActions.noOutput;
bool _appendEnter = true;
bool _validateSecretFormat = false;
bool _validatePublicIdFormat = false;
bool _validatePrivateIdFormat = false;
2023-11-17 15:02:51 +03:00
final secretLength = 32;
final publicIdLength = 12;
final privateIdLength = 12;
2023-11-09 16:09:59 +03:00
@override
void dispose() {
2023-11-17 15:02:51 +03:00
_secretController.dispose();
2023-11-09 16:09:59 +03:00
_publicIdController.dispose();
_privateIdController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final info = ref.watch(currentDeviceDataProvider).valueOrNull?.info;
2023-11-23 18:25:11 +03:00
final secret = _secretController.text;
2023-11-17 15:02:51 +03:00
final secretLengthValid = secret.length == secretLength;
2023-11-23 18:25:11 +03:00
final secretFormatValid = Format.hex.isValid(secret);
2023-11-17 15:02:51 +03:00
2023-11-09 16:09:59 +03:00
final privateId = _privateIdController.text;
2023-11-17 15:02:51 +03:00
final privateIdLengthValid = privateId.length == privateIdLength;
2023-11-23 18:25:11 +03:00
final privatedIdFormatValid = Format.hex.isValid(privateId);
2023-11-17 15:02:51 +03:00
final publicId = _publicIdController.text;
final publicIdLengthValid = publicId.length == publicIdLength;
2023-11-23 18:25:11 +03:00
final publicIdFormatValid = Format.modhex.isValid(publicId);
2023-11-17 15:02:51 +03:00
2023-11-23 18:25:11 +03:00
final lengthsValid =
2023-11-17 15:02:51 +03:00
secretLengthValid && privateIdLengthValid && publicIdLengthValid;
final outputFile = ref.read(yubiOtpOutputProvider);
_createUploadText(context, l10n);
Future<bool> selectFile() async {
2023-11-17 15:02:51 +03:00
final filePath = await FilePicker.platform.saveFile(
2023-12-14 18:55:57 +03:00
dialogTitle: l10n.l_export_configuration_file,
2023-11-17 15:02:51 +03:00
allowedExtensions: ['csv'],
type: FileType.custom,
lockParentWindow: true);
if (filePath == null) {
return false;
2023-11-17 15:02:51 +03:00
}
ref.read(yubiOtpOutputProvider.notifier).setOutput(File(filePath));
return true;
2023-11-17 15:02:51 +03:00
}
2023-11-09 16:09:59 +03:00
return ResponsiveDialog(
2024-01-29 11:19:51 +03:00
title: Text(l10n.s_capability_otp),
2023-11-09 16:09:59 +03:00
actions: [
TextButton(
key: keys.saveButton,
2023-11-23 18:25:11 +03:00
onPressed: lengthsValid
2023-11-17 15:02:51 +03:00
? () async {
2023-11-23 18:25:11 +03:00
if (!secretFormatValid ||
!publicIdFormatValid ||
!privatedIdFormatValid) {
setState(() {
_validateSecretFormat = !secretFormatValid;
_validatePublicIdFormat = !publicIdFormatValid;
_validatePrivateIdFormat = !privatedIdFormatValid;
});
return;
}
2023-11-09 16:09:59 +03:00
if (!await confirmOverwrite(context, widget.otpSlot)) {
return;
}
final otpNotifier =
ref.read(otpStateProvider(widget.devicePath).notifier);
2024-03-27 18:42:56 +03:00
final configuration = SlotConfiguration.yubiotp(
publicId: publicId,
privateId: privateId,
key: secret,
options:
SlotConfigurationOptions(appendCr: _appendEnter));
bool configurationSucceded = false;
2023-11-09 16:09:59 +03:00
try {
await otpNotifier.configureSlot(widget.otpSlot.slot,
2024-03-27 18:42:56 +03:00
configuration: configuration);
configurationSucceded = true;
} catch (e) {
_log.error('Failed to program credential', e);
// Access code required
await ref.read(withContextProvider)((context) async {
final result = await showBlurDialog(
context: context,
builder: (context) => AccessCodeDialog(
devicePath: widget.devicePath,
otpSlot: widget.otpSlot,
action: (accessCode) async {
await otpNotifier.configureSlot(
widget.otpSlot.slot,
configuration: configuration,
accessCode: accessCode);
},
));
configurationSucceded = result ?? false;
});
}
if (configurationSucceded) {
if (outputFile != null) {
2023-11-17 15:02:51 +03:00
final csv = await otpNotifier.formatYubiOtpCsv(
info!.serial!, publicId, privateId, secret);
await outputFile.writeAsString(
2023-11-17 15:02:51 +03:00
'$csv${Platform.lineTerminator}',
mode: FileMode.append);
}
2024-03-27 18:42:56 +03:00
}
await ref.read(withContextProvider)((context) async {
Navigator.of(context).pop();
if (configurationSucceded) {
2023-11-17 15:02:51 +03:00
showMessage(
context,
outputFile != null
2023-11-23 18:25:11 +03:00
? l10n.l_slot_credential_configured_and_exported(
2024-01-29 11:19:51 +03:00
l10n.s_capability_otp,
2023-11-23 18:25:11 +03:00
outputFile.uri.pathSegments.last)
: l10n.l_slot_credential_configured(
2024-01-29 11:19:51 +03:00
l10n.s_capability_otp));
2024-03-27 18:42:56 +03:00
}
});
2023-11-17 15:02:51 +03:00
}
: null,
2023-11-09 16:09:59 +03:00
child: Text(l10n.s_save),
)
],
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AppTextField(
2023-11-09 16:09:59 +03:00
key: keys.publicIdField,
autofocus: true,
controller: _publicIdController,
autofillHints: isAndroid ? [] : const [AutofillHints.password],
2023-11-17 15:02:51 +03:00
maxLength: publicIdLength,
2023-12-14 18:38:10 +03:00
decoration: AppInputDecoration(
border: const OutlineInputBorder(),
labelText: l10n.s_public_id,
errorText: _validatePublicIdFormat && !publicIdFormatValid
? l10n.l_invalid_format_allowed_chars(
Format.modhex.allowedCharacters)
: null,
2024-03-08 11:30:47 +03:00
prefixIcon: const Icon(Symbols.public),
2023-12-14 18:38:10 +03:00
suffixIcon: IconButton(
2024-02-08 22:47:26 +03:00
key: keys.useSerial,
2023-12-14 18:38:10 +03:00
tooltip: l10n.s_use_serial,
2024-03-08 11:30:47 +03:00
icon: const Icon(Symbols.auto_awesome),
2023-12-14 18:38:10 +03:00
onPressed: (info?.serial != null)
? () async {
final publicId = await ref
.read(otpStateProvider(widget.devicePath)
.notifier)
.modhexEncodeSerial(info!.serial!);
setState(() {
_publicIdController.text = publicId;
});
}
: null,
)),
2023-11-09 16:09:59 +03:00
textInputAction: TextInputAction.next,
2023-11-17 15:02:51 +03:00
onChanged: (value) {
setState(() {
2023-11-23 18:25:11 +03:00
_validatePublicIdFormat = false;
2023-11-17 15:02:51 +03:00
});
},
).init(),
AppTextField(
2023-11-09 16:09:59 +03:00
key: keys.privateIdField,
controller: _privateIdController,
autofillHints: isAndroid ? [] : const [AutofillHints.password],
2023-11-17 15:02:51 +03:00
maxLength: privateIdLength,
2023-12-14 18:38:10 +03:00
decoration: AppInputDecoration(
border: const OutlineInputBorder(),
labelText: l10n.s_private_id,
errorText: _validatePrivateIdFormat && !privatedIdFormatValid
? l10n.l_invalid_format_allowed_chars(
Format.hex.allowedCharacters)
: null,
2024-03-08 11:30:47 +03:00
prefixIcon: const Icon(Symbols.key),
2023-12-14 18:38:10 +03:00
suffixIcon: IconButton(
2024-02-08 22:47:26 +03:00
key: keys.generatePrivateId,
2023-12-14 18:38:10 +03:00
tooltip: l10n.s_generate_random,
2024-03-08 11:30:47 +03:00
icon: const Icon(Symbols.refresh),
2023-12-14 18:38:10 +03:00
onPressed: () {
final random = Random.secure();
final key = List.generate(
6,
(_) => random
.nextInt(256)
.toRadixString(16)
.padLeft(2, '0')).join();
setState(() {
_privateIdController.text = key;
});
},
)),
2023-11-09 16:09:59 +03:00
textInputAction: TextInputAction.next,
2023-11-17 15:02:51 +03:00
onChanged: (value) {
setState(() {
2023-11-23 18:25:11 +03:00
_validatePrivateIdFormat = false;
2023-11-17 15:02:51 +03:00
});
},
).init(),
AppTextField(
2023-11-09 16:09:59 +03:00
key: keys.secretField,
2023-11-17 15:02:51 +03:00
controller: _secretController,
2023-11-09 16:09:59 +03:00
autofillHints: isAndroid ? [] : const [AutofillHints.password],
2023-11-17 15:02:51 +03:00
maxLength: secretLength,
2023-12-14 18:38:10 +03:00
decoration: AppInputDecoration(
border: const OutlineInputBorder(),
labelText: l10n.s_secret_key,
errorText: _validateSecretFormat && !secretFormatValid
? l10n.l_invalid_format_allowed_chars(
Format.hex.allowedCharacters)
: null,
2024-03-08 11:30:47 +03:00
prefixIcon: const Icon(Symbols.key),
2023-12-14 18:38:10 +03:00
suffixIcon: IconButton(
2024-02-08 22:47:26 +03:00
key: keys.generateSecretKey,
2023-12-14 18:38:10 +03:00
tooltip: l10n.s_generate_random,
2024-03-08 11:30:47 +03:00
icon: const Icon(Symbols.refresh),
2023-12-14 18:38:10 +03:00
onPressed: () {
final random = Random.secure();
final key = List.generate(
16,
(_) => random
.nextInt(256)
.toRadixString(16)
.padLeft(2, '0')).join();
setState(() {
_secretController.text = key;
});
},
)),
2023-11-09 16:09:59 +03:00
textInputAction: TextInputAction.next,
2023-11-17 15:02:51 +03:00
onChanged: (value) {
setState(() {
2023-11-23 18:25:11 +03:00
_validateSecretFormat = false;
2023-11-17 15:02:51 +03:00
});
},
).init(),
2023-11-09 16:09:59 +03:00
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4.0,
runSpacing: 8.0,
children: [
FilterChip(
label: Text(l10n.s_append_enter),
tooltip: l10n.l_append_enter_desc,
selected: _appendEnter,
onSelected: (value) {
setState(() {
_appendEnter = value;
});
},
2023-11-17 15:02:51 +03:00
),
ChoiceFilterChip<OutputActions>(
2023-12-14 18:55:57 +03:00
tooltip: outputFile?.path ?? l10n.s_no_export,
selected: outputFile != null,
avatar: outputFile != null
2024-03-08 11:30:47 +03:00
? Icon(Symbols.check,
2023-11-17 15:02:51 +03:00
color: Theme.of(context).colorScheme.secondary)
: null,
value: _action,
items: OutputActions.values,
itemBuilder: (value) => Text(value.getDisplayName(l10n)),
labelBuilder: (_) {
String? fileName = outputFile?.uri.pathSegments.last;
2023-11-17 15:02:51 +03:00
return Container(
constraints: const BoxConstraints(maxWidth: 140),
child: Text(
2023-11-23 18:25:11 +03:00
fileName != null
2023-12-14 18:55:57 +03:00
? '${l10n.s_export} $fileName'
2023-11-23 18:25:11 +03:00
: _action.getDisplayName(l10n),
2023-11-17 15:02:51 +03:00
overflow: TextOverflow.ellipsis,
),
);
},
onChanged: (value) async {
if (value == OutputActions.noOutput) {
ref.read(yubiOtpOutputProvider.notifier).setOutput(null);
2023-11-17 15:02:51 +03:00
setState(() {
_action = value;
});
} else if (value == OutputActions.selectFile) {
if (await selectFile()) {
2023-11-17 15:02:51 +03:00
setState(() {
_action = value;
});
}
}
},
),
2023-11-09 16:09:59 +03:00
],
2024-03-21 17:54:21 +03:00
),
_createUploadText(context, l10n)
2023-11-09 16:09:59 +03:00
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: e,
))
.toList(),
),
),
);
}
2024-03-21 17:54:21 +03:00
RichText _createUploadText(BuildContext context, AppLocalizations l10n) {
final uploadText = l10n.l_exported_can_be_uploaded_at(uploadOtpUri.host);
final host = uploadOtpUri.host;
final parts = uploadText.split(RegExp('(?=$host)|(?<=$host)'));
return RichText(
text: TextSpan(
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
children: [
...parts.map(
(e) => e == uploadOtpUri.host
? _createUploadOtpLink(context)
: TextSpan(text: e),
)
],
),
);
}
2024-03-21 17:54:21 +03:00
TextSpan _createUploadOtpLink(BuildContext context) {
final theme = Theme.of(context);
return TextSpan(
text: uploadOtpUri.host,
2024-03-22 13:30:29 +03:00
style:
theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.primary),
2024-03-21 17:54:21 +03:00
recognizer: TapGestureRecognizer()
..onTap = () async {
await launchUrl(uploadOtpUri, mode: LaunchMode.externalApplication);
},
);
}
2023-11-09 16:09:59 +03:00
}