This commit is contained in:
Dain Nilsson 2021-11-23 13:01:21 +01:00
commit d9b5cdc951
No known key found for this signature in database
GPG Key ID: F04367096FBA95E8
28 changed files with 3231 additions and 48 deletions

View File

@ -27,3 +27,8 @@ linter:
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"

20
build.yaml Normal file
View File

@ -0,0 +1,20 @@
targets:
$default:
builders:
json_serializable:
options:
# Options configure how source code is generated for every
# `@JsonSerializable`-annotated class in the package.
field_rename: snake
#
# The default value for each is listed.
any_map: false
checked: false
constructor: ""
create_factory: true
create_to_json: true
disallow_unrecognized_keys: false
explicit_to_json: false
generic_argument_factories: false
ignore_unannotated: false
include_if_null: true

22
lib/about_page.dart Executable file
View File

@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
class AboutPage extends StatelessWidget {
const AboutPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('About Yubico Authenticator'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text('About placeholder'),
],
),
),
);
}
}

18
lib/app.dart Executable file
View File

@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class YubicoAuthenticatorApp extends StatelessWidget {
final Widget page;
const YubicoAuthenticatorApp({required this.page, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Yubico Authenticator',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: page,
);
}
}

22
lib/app/device_info_screen.dart Executable file
View File

@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
import 'models.dart';
class DeviceInfoScreen extends StatelessWidget {
final DeviceNode device;
const DeviceInfoScreen(this.device, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('YubiKey: ${device.name}'),
Text('Serial: ${device.info.serial}'),
Text('Version: ${device.info.version}'),
],
),
);
}
}

101
lib/app/main_page.dart Executable file
View File

@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'no_device_screen.dart';
import 'device_info_screen.dart';
import 'models.dart';
import 'state.dart';
import '../../about_page.dart';
import '../oath/views/oath_screen.dart';
class MainPage extends ConsumerWidget {
const MainPage({Key? key}) : super(key: key);
Widget _buildSubPage(SubPage subPage, DeviceNode device) {
// TODO: If page not supported by device, do something?
switch (subPage) {
case SubPage.authenticator:
return OathScreen(device);
case SubPage.yubikey:
return DeviceInfoScreen(device);
}
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final currentDevice = ref.watch(currentDeviceProvider);
final subPage = ref.watch(subPageProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Yubico Authenticator'),
actions: [
IconButton(
icon: const Icon(Icons.info),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => const AboutPage()),
);
},
)
],
),
drawer: MainPageDrawer(
subPage,
onSelect: (page) {
ref.read(subPageProvider.notifier).setSubPage(page);
Navigator.of(context).pop();
},
),
body: currentDevice == null
? const NoDeviceScreen()
: _buildSubPage(subPage, currentDevice),
);
}
}
extension on SubPage {
String get displayName {
switch (this) {
case SubPage.authenticator:
return 'Authenticator';
case SubPage.yubikey:
return 'YubiKey';
}
}
}
class MainPageDrawer extends StatelessWidget {
final SubPage currentSubPage;
final void Function(SubPage) onSelect;
const MainPageDrawer(this.currentSubPage, {required this.onSelect, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Hello'),
),
...SubPage.values.map((value) => ListTile(
title: Text(
value.displayName,
style: Theme.of(context).textTheme.headline6,
),
tileColor: value == currentSubPage ? Colors.blueGrey : null,
enabled: value != currentSubPage,
onTap: () {
onSelect(value);
},
)),
],
),
);
}
}

21
lib/app/models.dart Executable file
View File

@ -0,0 +1,21 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../management/models.dart';
part 'models.freezed.dart';
part 'models.g.dart';
enum SubPage { authenticator, yubikey }
@freezed
class DeviceNode with _$DeviceNode {
factory DeviceNode(
List<String> path,
int pid,
Transport transport,
String name,
DeviceInfo info,
) = _DeviceNode;
factory DeviceNode.fromJson(Map<String, dynamic> json) =>
_$DeviceNodeFromJson(json);
}

253
lib/app/models.freezed.dart Executable file
View File

@ -0,0 +1,253 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target
part of 'models.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more informations: https://github.com/rrousselGit/freezed#custom-getters-and-methods');
DeviceNode _$DeviceNodeFromJson(Map<String, dynamic> json) {
return _DeviceNode.fromJson(json);
}
/// @nodoc
class _$DeviceNodeTearOff {
const _$DeviceNodeTearOff();
_DeviceNode call(List<String> path, int pid, Transport transport, String name,
DeviceInfo info) {
return _DeviceNode(
path,
pid,
transport,
name,
info,
);
}
DeviceNode fromJson(Map<String, Object?> json) {
return DeviceNode.fromJson(json);
}
}
/// @nodoc
const $DeviceNode = _$DeviceNodeTearOff();
/// @nodoc
mixin _$DeviceNode {
List<String> get path => throw _privateConstructorUsedError;
int get pid => throw _privateConstructorUsedError;
Transport get transport => throw _privateConstructorUsedError;
String get name => throw _privateConstructorUsedError;
DeviceInfo get info => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$DeviceNodeCopyWith<DeviceNode> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $DeviceNodeCopyWith<$Res> {
factory $DeviceNodeCopyWith(
DeviceNode value, $Res Function(DeviceNode) then) =
_$DeviceNodeCopyWithImpl<$Res>;
$Res call(
{List<String> path,
int pid,
Transport transport,
String name,
DeviceInfo info});
$DeviceInfoCopyWith<$Res> get info;
}
/// @nodoc
class _$DeviceNodeCopyWithImpl<$Res> implements $DeviceNodeCopyWith<$Res> {
_$DeviceNodeCopyWithImpl(this._value, this._then);
final DeviceNode _value;
// ignore: unused_field
final $Res Function(DeviceNode) _then;
@override
$Res call({
Object? path = freezed,
Object? pid = freezed,
Object? transport = freezed,
Object? name = freezed,
Object? info = freezed,
}) {
return _then(_value.copyWith(
path: path == freezed
? _value.path
: path // ignore: cast_nullable_to_non_nullable
as List<String>,
pid: pid == freezed
? _value.pid
: pid // ignore: cast_nullable_to_non_nullable
as int,
transport: transport == freezed
? _value.transport
: transport // ignore: cast_nullable_to_non_nullable
as Transport,
name: name == freezed
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
info: info == freezed
? _value.info
: info // ignore: cast_nullable_to_non_nullable
as DeviceInfo,
));
}
@override
$DeviceInfoCopyWith<$Res> get info {
return $DeviceInfoCopyWith<$Res>(_value.info, (value) {
return _then(_value.copyWith(info: value));
});
}
}
/// @nodoc
abstract class _$DeviceNodeCopyWith<$Res> implements $DeviceNodeCopyWith<$Res> {
factory _$DeviceNodeCopyWith(
_DeviceNode value, $Res Function(_DeviceNode) then) =
__$DeviceNodeCopyWithImpl<$Res>;
@override
$Res call(
{List<String> path,
int pid,
Transport transport,
String name,
DeviceInfo info});
@override
$DeviceInfoCopyWith<$Res> get info;
}
/// @nodoc
class __$DeviceNodeCopyWithImpl<$Res> extends _$DeviceNodeCopyWithImpl<$Res>
implements _$DeviceNodeCopyWith<$Res> {
__$DeviceNodeCopyWithImpl(
_DeviceNode _value, $Res Function(_DeviceNode) _then)
: super(_value, (v) => _then(v as _DeviceNode));
@override
_DeviceNode get _value => super._value as _DeviceNode;
@override
$Res call({
Object? path = freezed,
Object? pid = freezed,
Object? transport = freezed,
Object? name = freezed,
Object? info = freezed,
}) {
return _then(_DeviceNode(
path == freezed
? _value.path
: path // ignore: cast_nullable_to_non_nullable
as List<String>,
pid == freezed
? _value.pid
: pid // ignore: cast_nullable_to_non_nullable
as int,
transport == freezed
? _value.transport
: transport // ignore: cast_nullable_to_non_nullable
as Transport,
name == freezed
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
info == freezed
? _value.info
: info // ignore: cast_nullable_to_non_nullable
as DeviceInfo,
));
}
}
/// @nodoc
@JsonSerializable()
class _$_DeviceNode implements _DeviceNode {
_$_DeviceNode(this.path, this.pid, this.transport, this.name, this.info);
factory _$_DeviceNode.fromJson(Map<String, dynamic> json) =>
_$$_DeviceNodeFromJson(json);
@override
final List<String> path;
@override
final int pid;
@override
final Transport transport;
@override
final String name;
@override
final DeviceInfo info;
@override
String toString() {
return 'DeviceNode(path: $path, pid: $pid, transport: $transport, name: $name, info: $info)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _DeviceNode &&
const DeepCollectionEquality().equals(other.path, path) &&
(identical(other.pid, pid) || other.pid == pid) &&
(identical(other.transport, transport) ||
other.transport == transport) &&
(identical(other.name, name) || other.name == name) &&
(identical(other.info, info) || other.info == info));
}
@override
int get hashCode => Object.hash(runtimeType,
const DeepCollectionEquality().hash(path), pid, transport, name, info);
@JsonKey(ignore: true)
@override
_$DeviceNodeCopyWith<_DeviceNode> get copyWith =>
__$DeviceNodeCopyWithImpl<_DeviceNode>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$_DeviceNodeToJson(this);
}
}
abstract class _DeviceNode implements DeviceNode {
factory _DeviceNode(List<String> path, int pid, Transport transport,
String name, DeviceInfo info) = _$_DeviceNode;
factory _DeviceNode.fromJson(Map<String, dynamic> json) =
_$_DeviceNode.fromJson;
@override
List<String> get path;
@override
int get pid;
@override
Transport get transport;
@override
String get name;
@override
DeviceInfo get info;
@override
@JsonKey(ignore: true)
_$DeviceNodeCopyWith<_DeviceNode> get copyWith =>
throw _privateConstructorUsedError;
}

30
lib/app/models.g.dart Executable file
View File

@ -0,0 +1,30 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_DeviceNode _$$_DeviceNodeFromJson(Map<String, dynamic> json) =>
_$_DeviceNode(
(json['path'] as List<dynamic>).map((e) => e as String).toList(),
json['pid'] as int,
$enumDecode(_$TransportEnumMap, json['transport']),
json['name'] as String,
DeviceInfo.fromJson(json['info'] as Map<String, dynamic>),
);
Map<String, dynamic> _$$_DeviceNodeToJson(_$_DeviceNode instance) =>
<String, dynamic>{
'path': instance.path,
'pid': instance.pid,
'transport': _$TransportEnumMap[instance.transport],
'name': instance.name,
'info': instance.info,
};
const _$TransportEnumMap = {
Transport.usb: 'usb',
Transport.nfc: 'nfc',
};

17
lib/app/no_device_screen.dart Executable file
View File

@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
class NoDeviceScreen extends StatelessWidget {
const NoDeviceScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text('Insert a YubiKey'),
],
),
);
}
}

89
lib/app/state.dart Executable file
View File

@ -0,0 +1,89 @@
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/rpc.dart';
import '../../core/state.dart';
import 'models.dart';
final attachedDevicesProvider =
StateNotifierProvider<AttachedDeviceNotifier, List<DeviceNode>>(
(ref) => AttachedDeviceNotifier(ref.watch(rpcProvider)));
class AttachedDeviceNotifier extends StateNotifier<List<DeviceNode>> {
final RpcSession _rpc;
late Timer _pollTimer;
int _usbState = -1;
AttachedDeviceNotifier(this._rpc) : super([]) {
_pollTimer = Timer(const Duration(milliseconds: 500), _pollUsb);
}
@override
void dispose() {
_pollTimer.cancel();
super.dispose();
}
void _pollUsb() async {
var scan = await _rpc.command('scan', ['usb']);
if (_usbState != scan['state']) {
var usbResult = await _rpc.command('get', ['usb']);
developer.log('USB state change',
name: 'controller', error: jsonEncode(usbResult));
_usbState = usbResult['data']['state'];
List<DeviceNode> devices = [];
for (String id in (usbResult['children'] as Map).keys) {
var path = ['usb', id];
var deviceResult = await _rpc.command('get', path);
devices
.add(DeviceNode.fromJson({'path': path, ...deviceResult['data']}));
}
if (mounted) {
state = devices;
}
}
if (mounted) {
_pollTimer = Timer(const Duration(milliseconds: 500), _pollUsb);
}
}
}
final currentDeviceProvider =
StateNotifierProvider<CurrentDeviceNotifier, DeviceNode?>((ref) {
final provider = CurrentDeviceNotifier();
ref.listen(attachedDevicesProvider, provider._updateAttachedDevices);
return provider;
});
class CurrentDeviceNotifier extends StateNotifier<DeviceNode?> {
CurrentDeviceNotifier() : super(null);
_updateAttachedDevices(List<DeviceNode>? previous, List<DeviceNode> devices) {
if (devices.isEmpty) {
state = null;
} else if (!devices.contains(state)) {
state = devices.first;
}
}
setCurrentDevice(DeviceNode device) {
state = device;
}
}
final subPageProvider = StateNotifierProvider<SubPageNotifier, SubPage>(
(ref) => SubPageNotifier(SubPage.authenticator));
class SubPageNotifier extends StateNotifier<SubPage> {
SubPageNotifier(SubPage state) : super(state);
void setSubPage(SubPage page) {
state = page;
}
}

0
lib/core/models.freezed.dart Normal file → Executable file
View File

0
lib/core/models.g.dart Normal file → Executable file
View File

26
lib/error_page.dart Executable file
View File

@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
class ErrorPage extends StatelessWidget {
final String error;
const ErrorPage({required this.error, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Application error'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
error,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}

View File

@ -6,9 +6,13 @@ import 'dart:developer' as developer;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app.dart';
import 'core/rpc.dart';
import 'core/state.dart';
import 'app/main_page.dart';
import 'error_page.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
@ -26,7 +30,7 @@ void main() async {
.toFilePath();
}
Widget screen;
Widget page;
List<Override> overrides = [
prefProvider.overrideWithValue(await SharedPreferences.getInstance())
];
@ -36,62 +40,19 @@ void main() async {
var rpc = await RpcSession.launch(exe!);
developer.log('ykman process started', name: 'main');
overrides.add(rpcProvider.overrideWithValue(rpc));
screen = const MyHomePage(
title: 'Flutter demo home page',
);
page = const MainPage();
} catch (e) {
developer.log('ykman process failed: $e', name: 'main');
screen = NoProcessScreen(error: e.toString());
page = ErrorPage(error: e.toString());
}
runApp(ProviderScope(
overrides: overrides,
child: YubicoAuthenticatorApp(screen: screen),
child: YubicoAuthenticatorApp(page: page),
));
}
// Used when the subprocess can't be found/launched.
class NoProcessScreen extends StatelessWidget {
final String error;
const NoProcessScreen({required this.error, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('No process'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
error,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}
class YubicoAuthenticatorApp extends StatelessWidget {
final Widget screen;
const YubicoAuthenticatorApp({required this.screen, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Yubico Authenticator',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: screen,
);
}
}
//TODO: Remove below this
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

55
lib/management/models.dart Executable file
View File

@ -0,0 +1,55 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import '../core/models.dart';
part 'models.freezed.dart';
part 'models.g.dart';
enum Transport { usb, nfc }
enum FormFactor {
@JsonValue(0)
unknown,
@JsonValue(1)
usbAKeychain,
@JsonValue(2)
usbANano,
@JsonValue(3)
usbCKeychain,
@JsonValue(4)
usbCNano,
@JsonValue(5)
usbCLightning,
@JsonValue(6)
usbABio,
@JsonValue(7)
usbCBio,
}
@freezed
class DeviceConfig with _$DeviceConfig {
factory DeviceConfig(
Map<Transport, int> enabledCapabilities,
int? autoEjectTimeout,
int? challengeResponseTimeout,
int? deviceFlags) = _DeviceConfig;
factory DeviceConfig.fromJson(Map<String, dynamic> json) =>
_$DeviceConfigFromJson(json);
}
@freezed
class DeviceInfo with _$DeviceInfo {
factory DeviceInfo(
DeviceConfig config,
int? serial,
Version version,
FormFactor formFactor,
Map<Transport, int> supportedCapabilities,
bool isLocked,
bool isFips,
bool isSky) = _DeviceInfo;
factory DeviceInfo.fromJson(Map<String, dynamic> json) =>
_$DeviceInfoFromJson(json);
}

View File

@ -0,0 +1,568 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target
part of 'models.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more informations: https://github.com/rrousselGit/freezed#custom-getters-and-methods');
DeviceConfig _$DeviceConfigFromJson(Map<String, dynamic> json) {
return _DeviceConfig.fromJson(json);
}
/// @nodoc
class _$DeviceConfigTearOff {
const _$DeviceConfigTearOff();
_DeviceConfig call(Map<Transport, int> enabledCapabilities,
int? autoEjectTimeout, int? challengeResponseTimeout, int? deviceFlags) {
return _DeviceConfig(
enabledCapabilities,
autoEjectTimeout,
challengeResponseTimeout,
deviceFlags,
);
}
DeviceConfig fromJson(Map<String, Object?> json) {
return DeviceConfig.fromJson(json);
}
}
/// @nodoc
const $DeviceConfig = _$DeviceConfigTearOff();
/// @nodoc
mixin _$DeviceConfig {
Map<Transport, int> get enabledCapabilities =>
throw _privateConstructorUsedError;
int? get autoEjectTimeout => throw _privateConstructorUsedError;
int? get challengeResponseTimeout => throw _privateConstructorUsedError;
int? get deviceFlags => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$DeviceConfigCopyWith<DeviceConfig> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $DeviceConfigCopyWith<$Res> {
factory $DeviceConfigCopyWith(
DeviceConfig value, $Res Function(DeviceConfig) then) =
_$DeviceConfigCopyWithImpl<$Res>;
$Res call(
{Map<Transport, int> enabledCapabilities,
int? autoEjectTimeout,
int? challengeResponseTimeout,
int? deviceFlags});
}
/// @nodoc
class _$DeviceConfigCopyWithImpl<$Res> implements $DeviceConfigCopyWith<$Res> {
_$DeviceConfigCopyWithImpl(this._value, this._then);
final DeviceConfig _value;
// ignore: unused_field
final $Res Function(DeviceConfig) _then;
@override
$Res call({
Object? enabledCapabilities = freezed,
Object? autoEjectTimeout = freezed,
Object? challengeResponseTimeout = freezed,
Object? deviceFlags = freezed,
}) {
return _then(_value.copyWith(
enabledCapabilities: enabledCapabilities == freezed
? _value.enabledCapabilities
: enabledCapabilities // ignore: cast_nullable_to_non_nullable
as Map<Transport, int>,
autoEjectTimeout: autoEjectTimeout == freezed
? _value.autoEjectTimeout
: autoEjectTimeout // ignore: cast_nullable_to_non_nullable
as int?,
challengeResponseTimeout: challengeResponseTimeout == freezed
? _value.challengeResponseTimeout
: challengeResponseTimeout // ignore: cast_nullable_to_non_nullable
as int?,
deviceFlags: deviceFlags == freezed
? _value.deviceFlags
: deviceFlags // ignore: cast_nullable_to_non_nullable
as int?,
));
}
}
/// @nodoc
abstract class _$DeviceConfigCopyWith<$Res>
implements $DeviceConfigCopyWith<$Res> {
factory _$DeviceConfigCopyWith(
_DeviceConfig value, $Res Function(_DeviceConfig) then) =
__$DeviceConfigCopyWithImpl<$Res>;
@override
$Res call(
{Map<Transport, int> enabledCapabilities,
int? autoEjectTimeout,
int? challengeResponseTimeout,
int? deviceFlags});
}
/// @nodoc
class __$DeviceConfigCopyWithImpl<$Res> extends _$DeviceConfigCopyWithImpl<$Res>
implements _$DeviceConfigCopyWith<$Res> {
__$DeviceConfigCopyWithImpl(
_DeviceConfig _value, $Res Function(_DeviceConfig) _then)
: super(_value, (v) => _then(v as _DeviceConfig));
@override
_DeviceConfig get _value => super._value as _DeviceConfig;
@override
$Res call({
Object? enabledCapabilities = freezed,
Object? autoEjectTimeout = freezed,
Object? challengeResponseTimeout = freezed,
Object? deviceFlags = freezed,
}) {
return _then(_DeviceConfig(
enabledCapabilities == freezed
? _value.enabledCapabilities
: enabledCapabilities // ignore: cast_nullable_to_non_nullable
as Map<Transport, int>,
autoEjectTimeout == freezed
? _value.autoEjectTimeout
: autoEjectTimeout // ignore: cast_nullable_to_non_nullable
as int?,
challengeResponseTimeout == freezed
? _value.challengeResponseTimeout
: challengeResponseTimeout // ignore: cast_nullable_to_non_nullable
as int?,
deviceFlags == freezed
? _value.deviceFlags
: deviceFlags // ignore: cast_nullable_to_non_nullable
as int?,
));
}
}
/// @nodoc
@JsonSerializable()
class _$_DeviceConfig implements _DeviceConfig {
_$_DeviceConfig(this.enabledCapabilities, this.autoEjectTimeout,
this.challengeResponseTimeout, this.deviceFlags);
factory _$_DeviceConfig.fromJson(Map<String, dynamic> json) =>
_$$_DeviceConfigFromJson(json);
@override
final Map<Transport, int> enabledCapabilities;
@override
final int? autoEjectTimeout;
@override
final int? challengeResponseTimeout;
@override
final int? deviceFlags;
@override
String toString() {
return 'DeviceConfig(enabledCapabilities: $enabledCapabilities, autoEjectTimeout: $autoEjectTimeout, challengeResponseTimeout: $challengeResponseTimeout, deviceFlags: $deviceFlags)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _DeviceConfig &&
const DeepCollectionEquality()
.equals(other.enabledCapabilities, enabledCapabilities) &&
(identical(other.autoEjectTimeout, autoEjectTimeout) ||
other.autoEjectTimeout == autoEjectTimeout) &&
(identical(
other.challengeResponseTimeout, challengeResponseTimeout) ||
other.challengeResponseTimeout == challengeResponseTimeout) &&
(identical(other.deviceFlags, deviceFlags) ||
other.deviceFlags == deviceFlags));
}
@override
int get hashCode => Object.hash(
runtimeType,
const DeepCollectionEquality().hash(enabledCapabilities),
autoEjectTimeout,
challengeResponseTimeout,
deviceFlags);
@JsonKey(ignore: true)
@override
_$DeviceConfigCopyWith<_DeviceConfig> get copyWith =>
__$DeviceConfigCopyWithImpl<_DeviceConfig>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$_DeviceConfigToJson(this);
}
}
abstract class _DeviceConfig implements DeviceConfig {
factory _DeviceConfig(
Map<Transport, int> enabledCapabilities,
int? autoEjectTimeout,
int? challengeResponseTimeout,
int? deviceFlags) = _$_DeviceConfig;
factory _DeviceConfig.fromJson(Map<String, dynamic> json) =
_$_DeviceConfig.fromJson;
@override
Map<Transport, int> get enabledCapabilities;
@override
int? get autoEjectTimeout;
@override
int? get challengeResponseTimeout;
@override
int? get deviceFlags;
@override
@JsonKey(ignore: true)
_$DeviceConfigCopyWith<_DeviceConfig> get copyWith =>
throw _privateConstructorUsedError;
}
DeviceInfo _$DeviceInfoFromJson(Map<String, dynamic> json) {
return _DeviceInfo.fromJson(json);
}
/// @nodoc
class _$DeviceInfoTearOff {
const _$DeviceInfoTearOff();
_DeviceInfo call(
DeviceConfig config,
int? serial,
Version version,
FormFactor formFactor,
Map<Transport, int> supportedCapabilities,
bool isLocked,
bool isFips,
bool isSky) {
return _DeviceInfo(
config,
serial,
version,
formFactor,
supportedCapabilities,
isLocked,
isFips,
isSky,
);
}
DeviceInfo fromJson(Map<String, Object?> json) {
return DeviceInfo.fromJson(json);
}
}
/// @nodoc
const $DeviceInfo = _$DeviceInfoTearOff();
/// @nodoc
mixin _$DeviceInfo {
DeviceConfig get config => throw _privateConstructorUsedError;
int? get serial => throw _privateConstructorUsedError;
Version get version => throw _privateConstructorUsedError;
FormFactor get formFactor => throw _privateConstructorUsedError;
Map<Transport, int> get supportedCapabilities =>
throw _privateConstructorUsedError;
bool get isLocked => throw _privateConstructorUsedError;
bool get isFips => throw _privateConstructorUsedError;
bool get isSky => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$DeviceInfoCopyWith<DeviceInfo> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $DeviceInfoCopyWith<$Res> {
factory $DeviceInfoCopyWith(
DeviceInfo value, $Res Function(DeviceInfo) then) =
_$DeviceInfoCopyWithImpl<$Res>;
$Res call(
{DeviceConfig config,
int? serial,
Version version,
FormFactor formFactor,
Map<Transport, int> supportedCapabilities,
bool isLocked,
bool isFips,
bool isSky});
$DeviceConfigCopyWith<$Res> get config;
$VersionCopyWith<$Res> get version;
}
/// @nodoc
class _$DeviceInfoCopyWithImpl<$Res> implements $DeviceInfoCopyWith<$Res> {
_$DeviceInfoCopyWithImpl(this._value, this._then);
final DeviceInfo _value;
// ignore: unused_field
final $Res Function(DeviceInfo) _then;
@override
$Res call({
Object? config = freezed,
Object? serial = freezed,
Object? version = freezed,
Object? formFactor = freezed,
Object? supportedCapabilities = freezed,
Object? isLocked = freezed,
Object? isFips = freezed,
Object? isSky = freezed,
}) {
return _then(_value.copyWith(
config: config == freezed
? _value.config
: config // ignore: cast_nullable_to_non_nullable
as DeviceConfig,
serial: serial == freezed
? _value.serial
: serial // ignore: cast_nullable_to_non_nullable
as int?,
version: version == freezed
? _value.version
: version // ignore: cast_nullable_to_non_nullable
as Version,
formFactor: formFactor == freezed
? _value.formFactor
: formFactor // ignore: cast_nullable_to_non_nullable
as FormFactor,
supportedCapabilities: supportedCapabilities == freezed
? _value.supportedCapabilities
: supportedCapabilities // ignore: cast_nullable_to_non_nullable
as Map<Transport, int>,
isLocked: isLocked == freezed
? _value.isLocked
: isLocked // ignore: cast_nullable_to_non_nullable
as bool,
isFips: isFips == freezed
? _value.isFips
: isFips // ignore: cast_nullable_to_non_nullable
as bool,
isSky: isSky == freezed
? _value.isSky
: isSky // ignore: cast_nullable_to_non_nullable
as bool,
));
}
@override
$DeviceConfigCopyWith<$Res> get config {
return $DeviceConfigCopyWith<$Res>(_value.config, (value) {
return _then(_value.copyWith(config: value));
});
}
@override
$VersionCopyWith<$Res> get version {
return $VersionCopyWith<$Res>(_value.version, (value) {
return _then(_value.copyWith(version: value));
});
}
}
/// @nodoc
abstract class _$DeviceInfoCopyWith<$Res> implements $DeviceInfoCopyWith<$Res> {
factory _$DeviceInfoCopyWith(
_DeviceInfo value, $Res Function(_DeviceInfo) then) =
__$DeviceInfoCopyWithImpl<$Res>;
@override
$Res call(
{DeviceConfig config,
int? serial,
Version version,
FormFactor formFactor,
Map<Transport, int> supportedCapabilities,
bool isLocked,
bool isFips,
bool isSky});
@override
$DeviceConfigCopyWith<$Res> get config;
@override
$VersionCopyWith<$Res> get version;
}
/// @nodoc
class __$DeviceInfoCopyWithImpl<$Res> extends _$DeviceInfoCopyWithImpl<$Res>
implements _$DeviceInfoCopyWith<$Res> {
__$DeviceInfoCopyWithImpl(
_DeviceInfo _value, $Res Function(_DeviceInfo) _then)
: super(_value, (v) => _then(v as _DeviceInfo));
@override
_DeviceInfo get _value => super._value as _DeviceInfo;
@override
$Res call({
Object? config = freezed,
Object? serial = freezed,
Object? version = freezed,
Object? formFactor = freezed,
Object? supportedCapabilities = freezed,
Object? isLocked = freezed,
Object? isFips = freezed,
Object? isSky = freezed,
}) {
return _then(_DeviceInfo(
config == freezed
? _value.config
: config // ignore: cast_nullable_to_non_nullable
as DeviceConfig,
serial == freezed
? _value.serial
: serial // ignore: cast_nullable_to_non_nullable
as int?,
version == freezed
? _value.version
: version // ignore: cast_nullable_to_non_nullable
as Version,
formFactor == freezed
? _value.formFactor
: formFactor // ignore: cast_nullable_to_non_nullable
as FormFactor,
supportedCapabilities == freezed
? _value.supportedCapabilities
: supportedCapabilities // ignore: cast_nullable_to_non_nullable
as Map<Transport, int>,
isLocked == freezed
? _value.isLocked
: isLocked // ignore: cast_nullable_to_non_nullable
as bool,
isFips == freezed
? _value.isFips
: isFips // ignore: cast_nullable_to_non_nullable
as bool,
isSky == freezed
? _value.isSky
: isSky // ignore: cast_nullable_to_non_nullable
as bool,
));
}
}
/// @nodoc
@JsonSerializable()
class _$_DeviceInfo implements _DeviceInfo {
_$_DeviceInfo(this.config, this.serial, this.version, this.formFactor,
this.supportedCapabilities, this.isLocked, this.isFips, this.isSky);
factory _$_DeviceInfo.fromJson(Map<String, dynamic> json) =>
_$$_DeviceInfoFromJson(json);
@override
final DeviceConfig config;
@override
final int? serial;
@override
final Version version;
@override
final FormFactor formFactor;
@override
final Map<Transport, int> supportedCapabilities;
@override
final bool isLocked;
@override
final bool isFips;
@override
final bool isSky;
@override
String toString() {
return 'DeviceInfo(config: $config, serial: $serial, version: $version, formFactor: $formFactor, supportedCapabilities: $supportedCapabilities, isLocked: $isLocked, isFips: $isFips, isSky: $isSky)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _DeviceInfo &&
(identical(other.config, config) || other.config == config) &&
(identical(other.serial, serial) || other.serial == serial) &&
(identical(other.version, version) || other.version == version) &&
(identical(other.formFactor, formFactor) ||
other.formFactor == formFactor) &&
const DeepCollectionEquality()
.equals(other.supportedCapabilities, supportedCapabilities) &&
(identical(other.isLocked, isLocked) ||
other.isLocked == isLocked) &&
(identical(other.isFips, isFips) || other.isFips == isFips) &&
(identical(other.isSky, isSky) || other.isSky == isSky));
}
@override
int get hashCode => Object.hash(
runtimeType,
config,
serial,
version,
formFactor,
const DeepCollectionEquality().hash(supportedCapabilities),
isLocked,
isFips,
isSky);
@JsonKey(ignore: true)
@override
_$DeviceInfoCopyWith<_DeviceInfo> get copyWith =>
__$DeviceInfoCopyWithImpl<_DeviceInfo>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$_DeviceInfoToJson(this);
}
}
abstract class _DeviceInfo implements DeviceInfo {
factory _DeviceInfo(
DeviceConfig config,
int? serial,
Version version,
FormFactor formFactor,
Map<Transport, int> supportedCapabilities,
bool isLocked,
bool isFips,
bool isSky) = _$_DeviceInfo;
factory _DeviceInfo.fromJson(Map<String, dynamic> json) =
_$_DeviceInfo.fromJson;
@override
DeviceConfig get config;
@override
int? get serial;
@override
Version get version;
@override
FormFactor get formFactor;
@override
Map<Transport, int> get supportedCapabilities;
@override
bool get isLocked;
@override
bool get isFips;
@override
bool get isSky;
@override
@JsonKey(ignore: true)
_$DeviceInfoCopyWith<_DeviceInfo> get copyWith =>
throw _privateConstructorUsedError;
}

69
lib/management/models.g.dart Executable file
View File

@ -0,0 +1,69 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_DeviceConfig _$$_DeviceConfigFromJson(Map<String, dynamic> json) =>
_$_DeviceConfig(
(json['enabled_capabilities'] as Map<String, dynamic>).map(
(k, e) => MapEntry($enumDecode(_$TransportEnumMap, k), e as int),
),
json['auto_eject_timeout'] as int?,
json['challenge_response_timeout'] as int?,
json['device_flags'] as int?,
);
Map<String, dynamic> _$$_DeviceConfigToJson(_$_DeviceConfig instance) =>
<String, dynamic>{
'enabled_capabilities': instance.enabledCapabilities
.map((k, e) => MapEntry(_$TransportEnumMap[k], e)),
'auto_eject_timeout': instance.autoEjectTimeout,
'challenge_response_timeout': instance.challengeResponseTimeout,
'device_flags': instance.deviceFlags,
};
const _$TransportEnumMap = {
Transport.usb: 'usb',
Transport.nfc: 'nfc',
};
_$_DeviceInfo _$$_DeviceInfoFromJson(Map<String, dynamic> json) =>
_$_DeviceInfo(
DeviceConfig.fromJson(json['config'] as Map<String, dynamic>),
json['serial'] as int?,
Version.fromJson(json['version'] as List<dynamic>),
$enumDecode(_$FormFactorEnumMap, json['form_factor']),
(json['supported_capabilities'] as Map<String, dynamic>).map(
(k, e) => MapEntry($enumDecode(_$TransportEnumMap, k), e as int),
),
json['is_locked'] as bool,
json['is_fips'] as bool,
json['is_sky'] as bool,
);
Map<String, dynamic> _$$_DeviceInfoToJson(_$_DeviceInfo instance) =>
<String, dynamic>{
'config': instance.config,
'serial': instance.serial,
'version': instance.version,
'form_factor': _$FormFactorEnumMap[instance.formFactor],
'supported_capabilities': instance.supportedCapabilities
.map((k, e) => MapEntry(_$TransportEnumMap[k], e)),
'is_locked': instance.isLocked,
'is_fips': instance.isFips,
'is_sky': instance.isSky,
};
const _$FormFactorEnumMap = {
FormFactor.unknown: 0,
FormFactor.usbAKeychain: 1,
FormFactor.usbANano: 2,
FormFactor.usbCKeychain: 3,
FormFactor.usbCNano: 4,
FormFactor.usbCLightning: 5,
FormFactor.usbABio: 6,
FormFactor.usbCBio: 7,
};

106
lib/oath/models.dart Executable file
View File

@ -0,0 +1,106 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'models.freezed.dart';
part 'models.g.dart';
enum HashAlgorithm {
@JsonValue(0x01)
sha1,
@JsonValue(0x02)
sha256,
@JsonValue(0x03)
sha512,
}
extension on HashAlgorithm {
String get name => toString().split('.').last.toUpperCase();
}
enum OathType {
@JsonValue(0x10)
hotp,
@JsonValue(0x20)
totp,
}
extension on OathType {
String get name => toString().split('.').last.toUpperCase();
}
@freezed
class OathCredential with _$OathCredential {
factory OathCredential(
String deviceId,
String id,
String? issuer,
String name,
OathType oathType,
int period,
bool touchRequired) = _OathCredential;
factory OathCredential.fromJson(Map<String, dynamic> json) =>
_$OathCredentialFromJson(json);
}
@freezed
class OathCode with _$OathCode {
factory OathCode(String value, int validFrom, int validTo) = _OathCode;
factory OathCode.fromJson(Map<String, dynamic> json) =>
_$OathCodeFromJson(json);
}
@freezed
class OathPair with _$OathPair {
factory OathPair(OathCredential credential, OathCode? code) = _OathPair;
}
@freezed
class OathState with _$OathState {
factory OathState(String deviceId, bool hasKey, bool locked) = _OathState;
factory OathState.fromJson(Map<String, dynamic> json) =>
_$OathStateFromJson(json);
}
@freezed
class CredentialData with _$CredentialData {
const CredentialData._();
factory CredentialData({
String? issuer,
required String name,
required String secret,
@Default(OathType.totp) OathType oathType,
@Default(HashAlgorithm.sha1) HashAlgorithm hashAlgorithm,
@Default(6) int digits,
@Default(30) int period,
@Default(0) int counter,
}) = _CredentialData;
factory CredentialData.fromJson(Map<String, dynamic> json) =>
_$CredentialDataFromJson(json);
Uri toUri() {
final path = issuer != null ? '$issuer:$name' : name;
var uri = 'otpauth://${oathType.name}/$path?secret=$secret';
switch (oathType) {
case OathType.hotp:
uri += '&counter=$counter';
break;
case OathType.totp:
uri += '&period=$period';
break;
}
if (issuer != null) {
uri += '&issuer=$issuer';
}
if (digits != 6) {
uri += '&digits=$digits';
}
if (hashAlgorithm != HashAlgorithm.sha1) {
uri += '&algorithm=${hashAlgorithm.name}';
}
return Uri.parse(uri);
}
}

1128
lib/oath/models.freezed.dart Executable file

File diff suppressed because it is too large Load Diff

93
lib/oath/models.g.dart Executable file
View File

@ -0,0 +1,93 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_OathCredential _$$_OathCredentialFromJson(Map<String, dynamic> json) =>
_$_OathCredential(
json['device_id'] as String,
json['id'] as String,
json['issuer'] as String?,
json['name'] as String,
$enumDecode(_$OathTypeEnumMap, json['oath_type']),
json['period'] as int,
json['touch_required'] as bool,
);
Map<String, dynamic> _$$_OathCredentialToJson(_$_OathCredential instance) =>
<String, dynamic>{
'device_id': instance.deviceId,
'id': instance.id,
'issuer': instance.issuer,
'name': instance.name,
'oath_type': _$OathTypeEnumMap[instance.oathType],
'period': instance.period,
'touch_required': instance.touchRequired,
};
const _$OathTypeEnumMap = {
OathType.hotp: 16,
OathType.totp: 32,
};
_$_OathCode _$$_OathCodeFromJson(Map<String, dynamic> json) => _$_OathCode(
json['value'] as String,
json['valid_from'] as int,
json['valid_to'] as int,
);
Map<String, dynamic> _$$_OathCodeToJson(_$_OathCode instance) =>
<String, dynamic>{
'value': instance.value,
'valid_from': instance.validFrom,
'valid_to': instance.validTo,
};
_$_OathState _$$_OathStateFromJson(Map<String, dynamic> json) => _$_OathState(
json['device_id'] as String,
json['has_key'] as bool,
json['locked'] as bool,
);
Map<String, dynamic> _$$_OathStateToJson(_$_OathState instance) =>
<String, dynamic>{
'device_id': instance.deviceId,
'has_key': instance.hasKey,
'locked': instance.locked,
};
_$_CredentialData _$$_CredentialDataFromJson(Map<String, dynamic> json) =>
_$_CredentialData(
issuer: json['issuer'] as String?,
name: json['name'] as String,
secret: json['secret'] as String,
oathType: $enumDecodeNullable(_$OathTypeEnumMap, json['oath_type']) ??
OathType.totp,
hashAlgorithm:
$enumDecodeNullable(_$HashAlgorithmEnumMap, json['hash_algorithm']) ??
HashAlgorithm.sha1,
digits: json['digits'] as int? ?? 6,
period: json['period'] as int? ?? 30,
counter: json['counter'] as int? ?? 0,
);
Map<String, dynamic> _$$_CredentialDataToJson(_$_CredentialData instance) =>
<String, dynamic>{
'issuer': instance.issuer,
'name': instance.name,
'secret': instance.secret,
'oath_type': _$OathTypeEnumMap[instance.oathType],
'hash_algorithm': _$HashAlgorithmEnumMap[instance.hashAlgorithm],
'digits': instance.digits,
'period': instance.period,
'counter': instance.counter,
};
const _$HashAlgorithmEnumMap = {
HashAlgorithm.sha1: 1,
HashAlgorithm.sha256: 2,
HashAlgorithm.sha512: 3,
};

258
lib/oath/state.dart Executable file
View File

@ -0,0 +1,258 @@
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/state.dart';
import 'models.dart';
final _sessionProvider =
Provider.autoDispose.family<RpcNodeSession, List<String>>(
(ref, devicePath) => RpcNodeSession(
ref.watch(rpcProvider),
devicePath,
['ccid', 'oath'],
() {
ref.refresh(_sessionProvider(devicePath));
},
),
);
final oathStateProvider = StateNotifierProvider.autoDispose
.family<OathStateNotifier, OathState?, List<String>>(
(ref, devicePath) =>
OathStateNotifier(ref.watch(_sessionProvider(devicePath)))..refresh(),
);
class OathStateNotifier extends StateNotifier<OathState?> {
final RpcNodeSession _session;
OathStateNotifier(this._session) : super(null);
refresh() async {
var result = await _session.command('get');
developer.log('application status',
name: 'oath', error: jsonEncode(result));
if (mounted) {
state = OathState.fromJson(result['data']);
}
}
Future<bool> unlock(String password) async {
var result =
await _session.command('derive', params: {'password': password});
var key = result['key'];
await _session.command('validate', params: {'key': key});
if (mounted) {
developer.log('UNLOCKED');
state = state?.copyWith(locked: false);
}
return true;
}
}
final credentialListProvider = StateNotifierProvider.autoDispose
.family<CredentialListNotifier, List<OathPair>?, List<String>>(
(ref, devicePath) {
return CredentialListNotifier(
ref.watch(_sessionProvider(devicePath)),
ref.watch(oathStateProvider(devicePath).select((s) => s?.locked ?? true)),
)..refresh();
},
);
extension on OathCredential {
bool get isSteam => issuer == 'Steam' && oathType == OathType.totp;
}
const String _steamCharTable = '23456789BCDFGHJKMNPQRTVWXY';
String _formatSteam(String response) {
final offset = int.parse(response.substring(response.length - 1), radix: 16);
var number =
int.parse(response.substring(offset * 2, offset * 2 + 8), radix: 16) &
0x7fffffff;
var value = '';
for (var i = 0; i < 5; i++) {
value += _steamCharTable[number % _steamCharTable.length];
number ~/= _steamCharTable.length;
}
return value;
}
class CredentialListNotifier extends StateNotifier<List<OathPair>?> {
final RpcNodeSession _session;
final bool _locked;
Timer? _timer;
CredentialListNotifier(this._session, this._locked) : super(null);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
@protected
set state(List<OathPair>? value) {
super.state = value != null ? List.unmodifiable(value) : null;
}
calculate(OathCredential credential) async {
OathCode code;
if (credential.isSteam) {
final timeStep = DateTime.now().millisecondsSinceEpoch ~/ 30000;
var result = await _session.command('calculate', target: [
'accounts',
credential.id
], params: {
'challenge': timeStep.toRadixString(16).padLeft(16, '0'),
});
code = OathCode(
_formatSteam(result['response']), timeStep * 30, (timeStep + 1) * 30);
} else {
var result =
await _session.command('code', target: ['accounts', credential.id]);
code = OathCode.fromJson(result);
}
developer.log('Calculate', name: 'oath', error: jsonEncode(code));
if (mounted) {
final creds = state!.toList();
final i = creds.indexWhere((e) => e.credential.id == credential.id);
state = creds..[i] = creds[i].copyWith(code: code);
}
}
addAccount(Uri otpauth, {bool requireTouch = false}) async {
var result = await _session.command('put', target: [
'accounts'
], params: {
'uri': otpauth.toString(),
'require_touch': requireTouch,
});
final credential = OathCredential.fromJson(result);
if (mounted) {
state = state!.toList()..add(OathPair(credential, null));
if (!requireTouch && credential.oathType == OathType.totp) {
calculate(credential);
}
}
}
refresh() async {
if (_locked) return;
developer.log('refreshing credentials...', name: 'oath');
var result = await _session.command('calculate_all', target: ['accounts']);
developer.log('Entries', name: 'oath', error: jsonEncode(result));
if (mounted) {
var current = state?.toList() ?? [];
for (var e in result['entries']) {
final credential = OathCredential.fromJson(e['credential']);
final code = e['code'] == null ? null : OathCode.fromJson(e['code']);
var i = current
.indexWhere((element) => element.credential.id == credential.id);
if (i < 0) {
current.add(OathPair(credential, code));
} else if (code != null) {
current[i] = current[i].copyWith(code: code);
}
}
state = current;
for (var pair in current.where((element) =>
(element.credential.isSteam && !element.credential.touchRequired))) {
await calculate(pair.credential);
}
_scheduleRefresh();
}
}
_scheduleRefresh() {
_timer?.cancel();
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final expirations = (state ?? [])
.where((pair) =>
pair.credential.oathType == OathType.totp &&
!pair.credential.touchRequired)
.map((e) => e.code)
.whereType<OathCode>()
.map((e) => e.validTo)
.where((time) => time > now);
if (expirations.isEmpty) {
_timer = null;
} else {
_timer = Timer(Duration(seconds: expirations.reduce(min) - now), refresh);
}
}
}
final favoriteProvider =
StateNotifierProvider.family<FavoriteNotifier, bool, String>(
(ref, credentialId) {
return FavoriteNotifier(ref.watch(prefProvider), credentialId);
},
);
class FavoriteNotifier extends StateNotifier<bool> {
final SharedPreferences prefs;
final String _key;
FavoriteNotifier._(this.prefs, this._key)
: super(prefs.getBool(_key) ?? false);
factory FavoriteNotifier(SharedPreferences prefs, String credentialId) {
return FavoriteNotifier._(prefs, 'OATH_STATE_FAVORITE_$credentialId');
}
toggleFavorite() async {
await prefs.setBool(_key, !state);
if (mounted) {
state = !state;
}
}
}
final searchFilterProvider =
StateNotifierProvider<SearchFilterNotifier, String>(
(ref) => SearchFilterNotifier());
class SearchFilterNotifier extends StateNotifier<String> {
SearchFilterNotifier() : super('');
setFilter(String value) {
state = value;
}
}
final filteredCredentialsProvider = StateNotifierProvider.autoDispose
.family<FilteredCredentialsNotifier, List<OathPair>, List<OathPair>>(
(ref, full) {
final favorites = {
for (var credential in full.map((e) => e.credential))
credential: ref.watch(favoriteProvider(credential.id))
};
return FilteredCredentialsNotifier(
full, favorites, ref.watch(searchFilterProvider));
});
class FilteredCredentialsNotifier extends StateNotifier<List<OathPair>> {
final Map<OathCredential, bool> favorites;
final String query;
FilteredCredentialsNotifier(
List<OathPair> full,
this.favorites,
this.query,
) : super(full
.where((pair) =>
"${pair.credential.issuer ?? ''}:${pair.credential.name}"
.toLowerCase()
.contains(query.toLowerCase()))
.toList()
..sort((a, b) {
String searchKey(OathCredential c) =>
(favorites[c] == true ? '0' : '1') + (c.issuer ?? '') + c.name;
return searchKey(a.credential).compareTo(searchKey(b.credential));
}));
}

View File

@ -0,0 +1,30 @@
import 'package:flutter/material.dart';
import '../../app/models.dart';
import '../models.dart';
import 'account_view.dart';
class AccountList extends StatelessWidget {
final DeviceNode device;
final List<OathPair> credentials;
const AccountList(this.device, this.credentials, {Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
if (credentials.isEmpty) {
return const Center(
child: Text('No credentials'),
);
}
return ListView(
shrinkWrap: true,
children: [
...credentials.map(
(entry) => AccountView(device, entry.credential, entry.code),
),
],
);
}
}

View File

@ -0,0 +1,97 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/circle_timer.dart';
import '../../app/models.dart';
import '../models.dart';
import '../state.dart';
class AccountView extends ConsumerWidget {
final DeviceNode device;
final OathCredential credential;
final OathCode? code;
const AccountView(this.device, this.credential, this.code, {Key? key})
: super(key: key);
bool get _expired =>
(code?.validTo ?? 0) * 1000 < DateTime.now().millisecondsSinceEpoch;
String get _avatarLetter {
var name = credential.issuer ?? credential.name;
return name.substring(0, 1).toUpperCase();
}
String get _label => '${credential.issuer} (${credential.name})';
String get _code {
var value = code?.value;
if (value == null) {
return '••• •••';
} else if (value.length < 6) {
return value;
} else {
var i = value.length ~/ 2;
return value.substring(0, i) + ' ' + value.substring(i);
}
}
Color get _color =>
Colors.primaries.elementAt(_label.hashCode % Colors.primaries.length);
@override
Widget build(BuildContext context, WidgetRef ref) {
final favorite = ref.watch(favoriteProvider(credential.id));
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(children: [
CircleAvatar(
backgroundColor: _color,
child: Text(_avatarLetter, style: const TextStyle(fontSize: 18)),
),
const SizedBox(width: 8.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_code,
style: _expired
? Theme.of(context)
.textTheme
.headline6
?.copyWith(color: Colors.grey)
: Theme.of(context).textTheme.headline6),
Text(_label, style: Theme.of(context).textTheme.caption),
],
),
const Spacer(),
Row(
children: [
IconButton(
onPressed: () {
ref
.read(favoriteProvider(credential.id).notifier)
.toggleFavorite();
},
icon: Icon(favorite ? Icons.star : Icons.star_border),
),
SizedBox.square(
dimension: 16,
child: code != null && code!.validTo - code!.validFrom < 600
? CircleTimer(code!.validFrom * 1000, code!.validTo * 1000)
: null,
),
if (code == null)
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () {
ref
.read(credentialListProvider(device.path).notifier)
.calculate(credential);
},
)
],
),
]),
);
}
}

View File

@ -0,0 +1,30 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/state.dart';
import '../../app/models.dart';
class OathAddAccountPage extends ConsumerWidget {
final DeviceNode device;
const OathAddAccountPage({required this.device, Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
// If current device changes, we need to pop back to the main Page.
ref.listen<DeviceNode?>(currentDeviceProvider, (previous, next) {
//TODO: This can probably be checked better to make sure it's the main page.
Navigator.of(context).popUntil((route) => route.isFirst);
});
return Scaffold(
appBar: AppBar(
title: const Text('Add account'),
),
body: Column(
children: [
Text('Placeholder. Add account to ${device.name}'),
],
),
);
}
}

62
lib/oath/views/oath_screen.dart Executable file
View File

@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/models.dart';
import '../state.dart';
import 'account_list.dart';
import 'add_account_page.dart';
class OathScreen extends ConsumerWidget {
final DeviceNode device;
const OathScreen(this.device, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(oathStateProvider(device.path));
if (state == null) {
return const CircularProgressIndicator();
}
if (state.locked) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('YubiKey: ${device.name}'),
Text('OATH ID: ${state.deviceId}'),
],
),
);
} else {
final accounts = ref.watch(credentialListProvider(device.path));
if (accounts == null) {
return Column(
children: const [
Text('Reading...'),
],
);
}
return Column(
children: [
TextField(
onChanged: (value) {
ref.read(searchFilterProvider.notifier).setFilter(value);
},
decoration: const InputDecoration(labelText: 'Search'),
),
AccountList(device, ref.watch(filteredCredentialsProvider(accounts))),
TextButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => OathAddAccountPage(device: device)),
);
},
child: const Text('Add'),
),
],
);
}
}
}

63
lib/widgets/circle_timer.dart Executable file
View File

@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
import 'progress_circle.dart';
class CircleTimer extends StatefulWidget {
final int validFromMs;
final int validToMs;
const CircleTimer(this.validFromMs, this.validToMs, {Key? key})
: super(key: key);
@override
State<StatefulWidget> createState() => _CircleTimerState();
}
class _CircleTimerState extends State<CircleTimer>
with SingleTickerProviderStateMixin {
late AnimationController _animator;
late Tween<double> _tween;
late Animation<double> _progress;
void _animate() {
var period = widget.validToMs - widget.validFromMs;
var now = DateTime.now().millisecondsSinceEpoch;
_tween.begin = 1.0 - (now - widget.validFromMs) / period;
var timeLeft = widget.validToMs - now;
if (timeLeft > 0) {
_animator.duration = Duration(milliseconds: timeLeft.toInt());
_animator.forward();
}
}
@override
void initState() {
super.initState();
_animator = AnimationController(vsync: this);
_tween = Tween(end: 0);
_progress = _tween.animate(_animator)
..addListener(() {
setState(() {});
});
_animate();
}
@override
void didUpdateWidget(CircleTimer oldWidget) {
super.didUpdateWidget(oldWidget);
_animator.reset();
_animate();
}
@override
void dispose() {
_animator.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ProgressCircle(Colors.grey, _progress.value);
}
}

View File

@ -0,0 +1,39 @@
import 'dart:math';
import 'package:flutter/material.dart';
class ProgressCircle extends StatelessWidget {
final Color color;
final double progress;
const ProgressCircle(this.color, this.progress, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: _CirclePainter(color, progress),
);
}
}
class _CirclePainter extends CustomPainter {
final Color color;
final double progress;
_CirclePainter(this.color, this.progress);
@override
void paint(Canvas canvas, Size size) {
var radius = min(size.width, size.height) / 2;
canvas.drawArc(
Rect.fromCircle(center: Offset(radius, radius), radius: radius),
-pi / 2,
-progress * 2 * pi,
true,
Paint()..color = color,
);
}
@override
bool shouldRepaint(_CirclePainter oldDelegate) {
return oldDelegate.progress != progress || oldDelegate.color != color;
}
}