Merge 'main' into test/oath-integration-test

This commit is contained in:
Adam Velebil 2022-09-09 12:36:53 +02:00
commit c7ea6bad53
No known key found for this signature in database
GPG Key ID: AC6D6B9D715FC084
166 changed files with 6631 additions and 3977 deletions

View File

@ -16,6 +16,7 @@ jobs:
uses: subosito/flutter-action@v2 uses: subosito/flutter-action@v2
with: with:
channel: 'stable' channel: 'stable'
flutter-version: '3.0.5'
- run: | - run: |
flutter config flutter config
flutter --version flutter --version
@ -36,6 +37,10 @@ jobs:
flutter analyze flutter analyze
working-directory: ./app working-directory: ./app
- name: Generate Third party licenses
run: ./gradlew collectLicenses
working-directory: ./app/android
- name: Build the App - name: Build the App
run: flutter build apk --release run: flutter build apk --release
env: env:

View File

@ -33,6 +33,7 @@ jobs:
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
channel: 'stable' channel: 'stable'
flutter-version: '3.0.5'
- run: flutter config --enable-linux-desktop - run: flutter config --enable-linux-desktop
- run: flutter --version - run: flutter --version

View File

@ -31,6 +31,7 @@ jobs:
with: with:
channel: 'stable' channel: 'stable'
architecture: 'x64' architecture: 'x64'
flutter-version: '3.0.5'
- run: flutter config --enable-macos-desktop - run: flutter config --enable-macos-desktop
- run: flutter --version - run: flutter --version

View File

@ -29,6 +29,7 @@ jobs:
- uses: subosito/flutter-action@v2 - uses: subosito/flutter-action@v2
with: with:
channel: 'stable' channel: 'stable'
flutter-version: '3.0.5'
- run: flutter config --enable-windows-desktop - run: flutter config --enable-windows-desktop
- run: flutter --version - run: flutter --version

26
.metadata Normal file → Executable file
View File

@ -1,10 +1,30 @@
# This file tracks properties of this Flutter project. # This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc. # Used by Flutter tool to assess capabilities and perform upgrades etc.
# #
# This file should be version controlled and should not be manually edited. # This file should be version controlled.
version: version:
revision: 2901cd720879ba3d7ba7cbd7d447ec9e80f937b6 revision: ffccd96b62ee8cec7740dab303538c5fc26ac543
channel: beta channel: stable
project_type: app project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: ffccd96b62ee8cec7740dab303538c5fc26ac543
base_revision: ffccd96b62ee8cec7740dab303538c5fc26ac543
- platform: windows
create_revision: ffccd96b62ee8cec7740dab303538c5fc26ac543
base_revision: ffccd96b62ee8cec7740dab303538c5fc26ac543
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

3
android/.gitignore vendored
View File

@ -1,8 +1,5 @@
gradle-wrapper.jar
/.gradle /.gradle
/captures/ /captures/
/gradlew
/gradlew.bat
/local.properties /local.properties
GeneratedPluginRegistrant.java GeneratedPluginRegistrant.java

View File

@ -27,10 +27,11 @@ apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'kotlinx-serialization' apply plugin: 'kotlinx-serialization'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
android { android {
compileSdkVersion flutter.compileSdkVersion compileSdkVersion 32
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
@ -46,7 +47,7 @@ android {
} }
defaultConfig { defaultConfig {
applicationId "com.yubico.yubioath" applicationId "com.yubico.yubioath.preview"
minSdkVersion project.minSdkVersion minSdkVersion project.minSdkVersion
targetSdkVersion project.targetSdkVersion targetSdkVersion project.targetSdkVersion
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
@ -68,6 +69,7 @@ android {
} }
apply from: "signing.gradle" apply from: "signing.gradle"
apply from: "collect_licenses.gradle"
flutter { flutter {
source '../..' source '../..'
@ -79,16 +81,19 @@ dependencies {
api "com.yubico.yubikit:oath:$project.yubiKitVersion" api "com.yubico.yubikit:oath:$project.yubiKitVersion"
api "com.yubico.yubikit:support:$project.yubiKitVersion" api "com.yubico.yubikit:support:$project.yubiKitVersion"
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC' implementation 'org.jetbrains.kotlinx:kotlinx-serialization-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2' implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2'
// Lifecycle // Lifecycle
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.fragment:fragment-ktx:1.4.1' implementation 'androidx.fragment:fragment-ktx:1.5.2'
implementation 'androidx.preference:preference-ktx:1.2.0'
// testing dependencies // testing dependencies
testImplementation "junit:junit:$project.junitVersion" testImplementation "junit:junit:$project.junitVersion"
testImplementation "org.mockito:mockito-core:$project.mockitoVersion" testImplementation "org.mockito:mockito-core:$project.mockitoVersion"
testImplementation 'android.arch.core:core-testing:1.1.1'
} }

View File

@ -0,0 +1,91 @@
import groovy.json.JsonOutput
import java.util.regex.Pattern
def collectLicenses(File rootDir, File ossPluginResDir, File outDir) {
def pattern = Pattern.compile("^(\\d+:\\d+) (.*)\$")
// third_party_licenses file generated by oss-licenses-plugin
def licenses = new File(ossPluginResDir, "third_party_licenses")
// third_party_license_metadata file generated by oss-licenses-plugin
def metadata = new File(ossPluginResDir, "third_party_license_metadata")
// check that files exist, are readable and output directory is writable
if (!licenses.canRead()) {
throw new GradleException("Cannot find/read ${licenses.absolutePath}")
}
if (!metadata.canRead()) {
throw new GradleException("Cannot find/read ${metadata.absolutePath}")
}
if (!outDir.exists() || !outDir.canExecute()) {
if (!outDir.mkdir()) {
throw new GradleException("Failed to create ${outDir.absolutePath}")
}
}
def outFile = new File(outDir, "android.json")
if (outFile.exists()) {
outFile.delete()
}
println "Used licenses:"
var licenseMap = [:]
var index = 0
licenses.eachLine { line ->
def indices = "$index:${line.length()}"
println line
licenseMap[indices] = line
index += line.length() + 1
}
println "Modules:"
def licenseList = []
metadata.eachLine { line ->
def matcher = pattern.matcher(line)
if (matcher.find()) {
def indices = matcher.group(1)
def packageName = matcher.group(2)
if (licenseMap.get(indices) == null) {
throw new GradleException("Unexpected license indexes: $indices for $packageName")
}
println packageName + " license: ${licenseMap[indices]}"
licenseList.add(PackageName: packageName, PackageLicense: licenseMap[indices])
} else {
throw new GradleException("Unexpected project license line: $line")
}
}
// add zxing_licenses which are not detected
println "adding zxing licenses"
licenseList.add(PackageName: "ZXing Core (3.3.0)", PackageLicense: "https://www.apache.org/licenses/LICENSE-2.0.txt")
licenseList.add(PackageName: "ZXing Android Core (3.3.0)", PackageLicense: "https://www.apache.org/licenses/LICENSE-2.0.txt")
outFile.write(new JsonOutput().toJson(licenseList))
println "Created ${outFile.absolutePath}"
// copy license assets to flutter resources
def licensesDir = new File(rootDir, "licenses/");
copy {
from(licensesDir.absolutePath) {
include "**/*txt"
include "**/*json"
}
into outDir
}
// remove not needed oss-licenses-plugin files
licenses.delete()
metadata.delete()
}
task collectLicenses() {
dependsOn(":app:releaseOssLicensesTask")
doLast {
def ossPluginResDir = new File(project.buildDir, "generated/third_party_licenses/release/res/raw/")
collectLicenses(project.rootDir, ossPluginResDir, new File(project.rootDir.parent, "assets/licenses/android/"))
}
}

View File

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yubico.authenticator"> package="com.yubico.authenticator">
@ -15,15 +16,18 @@
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_label"> android:label="@string/app_label">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:exported="true" android:exported="true"
android:hardwareAccelerated="true" android:hardwareAccelerated="true"
android:launchMode="singleTop" android:launchMode="singleTask"
android:resizeableActivity="false"
android:screenOrientation="portrait" android:screenOrientation="portrait"
android:theme="@style/LaunchTheme" android:theme="@style/LaunchTheme"
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as <!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues while the Flutter UI initializes. After that, this theme continues
@ -41,10 +45,27 @@
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" /> android:resource="@xml/device_filter" />
</activity> </activity>
<activity
android:name=".NdefActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/NdefActivityTheme">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:host="my.yubico.com"
android:scheme="https" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below. <!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data <meta-data
android:name="flutterEmbedding" android:name="flutterEmbedding"
android:value="2" /> android:value="2" />
</application> </application>
</manifest> </manifest>

View File

@ -1,662 +0,0 @@
// Autogenerated from Pigeon (v3.1.6), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package com.yubico.authenticator.api;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"})
public class Pigeon {
/** Generated class from Pigeon that represents data sent in messages. */
public static class UnlockResponse {
private @Nullable Boolean isUnlocked;
public @Nullable Boolean getIsUnlocked() { return isUnlocked; }
public void setIsUnlocked(@Nullable Boolean setterArg) {
this.isUnlocked = setterArg;
}
private @Nullable Boolean isRemembered;
public @Nullable Boolean getIsRemembered() { return isRemembered; }
public void setIsRemembered(@Nullable Boolean setterArg) {
this.isRemembered = setterArg;
}
public static final class Builder {
private @Nullable Boolean isUnlocked;
public @NonNull Builder setIsUnlocked(@Nullable Boolean setterArg) {
this.isUnlocked = setterArg;
return this;
}
private @Nullable Boolean isRemembered;
public @NonNull Builder setIsRemembered(@Nullable Boolean setterArg) {
this.isRemembered = setterArg;
return this;
}
public @NonNull UnlockResponse build() {
UnlockResponse pigeonReturn = new UnlockResponse();
pigeonReturn.setIsUnlocked(isUnlocked);
pigeonReturn.setIsRemembered(isRemembered);
return pigeonReturn;
}
}
@NonNull Map<String, Object> toMap() {
Map<String, Object> toMapResult = new HashMap<>();
toMapResult.put("isUnlocked", isUnlocked);
toMapResult.put("isRemembered", isRemembered);
return toMapResult;
}
static @NonNull UnlockResponse fromMap(@NonNull Map<String, Object> map) {
UnlockResponse pigeonResult = new UnlockResponse();
Object isUnlocked = map.get("isUnlocked");
pigeonResult.setIsUnlocked((Boolean)isUnlocked);
Object isRemembered = map.get("isRemembered");
pigeonResult.setIsRemembered((Boolean)isRemembered);
return pigeonResult;
}
}
public interface Result<T> {
void success(T result);
void error(Throwable error);
}
private static class OathApiCodec extends StandardMessageCodec {
public static final OathApiCodec INSTANCE = new OathApiCodec();
private OathApiCodec() {}
@Override
protected Object readValueOfType(byte type, ByteBuffer buffer) {
switch (type) {
case (byte)128:
return UnlockResponse.fromMap((Map<String, Object>) readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(ByteArrayOutputStream stream, Object value) {
if (value instanceof UnlockResponse) {
stream.write(128);
writeValue(stream, ((UnlockResponse) value).toMap());
} else
{
super.writeValue(stream, value);
}
}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter.*/
public interface OathApi {
void reset(Result<Void> result);
void unlock(@NonNull String password, @NonNull Boolean remember, Result<UnlockResponse> result);
void setPassword(@Nullable String currentPassword, @NonNull String newPassword, Result<Void> result);
void unsetPassword(@NonNull String currentPassword, Result<Void> result);
void forgetPassword(Result<Void> result);
void addAccount(@NonNull String uri, @NonNull Boolean requireTouch, Result<String> result);
void renameAccount(@NonNull String uri, @NonNull String name, @Nullable String issuer, Result<String> result);
void deleteAccount(@NonNull String uri, Result<Void> result);
void refreshCodes(Result<String> result);
void calculate(@NonNull String uri, Result<String> result);
/** The codec used by OathApi. */
static MessageCodec<Object> getCodec() {
return OathApiCodec.INSTANCE;
}
/** Sets up an instance of `OathApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, OathApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.reset", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.reset(resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.unlock", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String passwordArg = (String)args.get(0);
if (passwordArg == null) {
throw new NullPointerException("passwordArg unexpectedly null.");
}
Boolean rememberArg = (Boolean)args.get(1);
if (rememberArg == null) {
throw new NullPointerException("rememberArg unexpectedly null.");
}
Result<UnlockResponse> resultCallback = new Result<UnlockResponse>() {
public void success(UnlockResponse result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.unlock(passwordArg, rememberArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.setPassword", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String currentPasswordArg = (String)args.get(0);
String newPasswordArg = (String)args.get(1);
if (newPasswordArg == null) {
throw new NullPointerException("newPasswordArg unexpectedly null.");
}
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.setPassword(currentPasswordArg, newPasswordArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.unsetPassword", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String currentPasswordArg = (String)args.get(0);
if (currentPasswordArg == null) {
throw new NullPointerException("currentPasswordArg unexpectedly null.");
}
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.unsetPassword(currentPasswordArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.forgetPassword", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.forgetPassword(resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.addAccount", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String uriArg = (String)args.get(0);
if (uriArg == null) {
throw new NullPointerException("uriArg unexpectedly null.");
}
Boolean requireTouchArg = (Boolean)args.get(1);
if (requireTouchArg == null) {
throw new NullPointerException("requireTouchArg unexpectedly null.");
}
Result<String> resultCallback = new Result<String>() {
public void success(String result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.addAccount(uriArg, requireTouchArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.renameAccount", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String uriArg = (String)args.get(0);
if (uriArg == null) {
throw new NullPointerException("uriArg unexpectedly null.");
}
String nameArg = (String)args.get(1);
if (nameArg == null) {
throw new NullPointerException("nameArg unexpectedly null.");
}
String issuerArg = (String)args.get(2);
Result<String> resultCallback = new Result<String>() {
public void success(String result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.renameAccount(uriArg, nameArg, issuerArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.deleteAccount", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String uriArg = (String)args.get(0);
if (uriArg == null) {
throw new NullPointerException("uriArg unexpectedly null.");
}
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.deleteAccount(uriArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.refreshCodes", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
Result<String> resultCallback = new Result<String>() {
public void success(String result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.refreshCodes(resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.OathApi.calculate", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String uriArg = (String)args.get(0);
if (uriArg == null) {
throw new NullPointerException("uriArg unexpectedly null.");
}
Result<String> resultCallback = new Result<String>() {
public void success(String result) {
wrapped.put("result", result);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.calculate(uriArg, resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static class AppApiCodec extends StandardMessageCodec {
public static final AppApiCodec INSTANCE = new AppApiCodec();
private AppApiCodec() {}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter.*/
public interface AppApi {
void setContext(@NonNull Long subPageIndex, Result<Void> result);
/** The codec used by AppApi. */
static MessageCodec<Object> getCodec() {
return AppApiCodec.INSTANCE;
}
/** Sets up an instance of `AppApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, AppApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.AppApi.setContext", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
Number subPageIndexArg = (Number)args.get(0);
if (subPageIndexArg == null) {
throw new NullPointerException("subPageIndexArg unexpectedly null.");
}
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.setContext((subPageIndexArg == null) ? null : subPageIndexArg.longValue(), resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static class FOathApiCodec extends StandardMessageCodec {
public static final FOathApiCodec INSTANCE = new FOathApiCodec();
private FOathApiCodec() {}
}
/** Generated class from Pigeon that represents Flutter messages that can be called from Java.*/
public static class FOathApi {
private final BinaryMessenger binaryMessenger;
public FOathApi(BinaryMessenger argBinaryMessenger){
this.binaryMessenger = argBinaryMessenger;
}
public interface Reply<T> {
void reply(T reply);
}
static MessageCodec<Object> getCodec() {
return FOathApiCodec.INSTANCE;
}
public void updateSession(@NonNull String sessionJsonArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.FOathApi.updateSession", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(sessionJsonArg)), channelReply -> {
callback.reply(null);
});
}
public void updateOathCredentials(@NonNull String credentialListJsonArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.FOathApi.updateOathCredentials", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(credentialListJsonArg)), channelReply -> {
callback.reply(null);
});
}
}
private static class FManagementApiCodec extends StandardMessageCodec {
public static final FManagementApiCodec INSTANCE = new FManagementApiCodec();
private FManagementApiCodec() {}
}
/** Generated class from Pigeon that represents Flutter messages that can be called from Java.*/
public static class FManagementApi {
private final BinaryMessenger binaryMessenger;
public FManagementApi(BinaryMessenger argBinaryMessenger){
this.binaryMessenger = argBinaryMessenger;
}
public interface Reply<T> {
void reply(T reply);
}
static MessageCodec<Object> getCodec() {
return FManagementApiCodec.INSTANCE;
}
public void updateDeviceInfo(@NonNull String deviceInfoJsonArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.FManagementApi.updateDeviceInfo", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(deviceInfoJsonArg)), channelReply -> {
callback.reply(null);
});
}
}
private static class FDialogApiCodec extends StandardMessageCodec {
public static final FDialogApiCodec INSTANCE = new FDialogApiCodec();
private FDialogApiCodec() {}
}
/** Generated class from Pigeon that represents Flutter messages that can be called from Java.*/
public static class FDialogApi {
private final BinaryMessenger binaryMessenger;
public FDialogApi(BinaryMessenger argBinaryMessenger){
this.binaryMessenger = argBinaryMessenger;
}
public interface Reply<T> {
void reply(T reply);
}
static MessageCodec<Object> getCodec() {
return FDialogApiCodec.INSTANCE;
}
public void showDialogApi(@NonNull String dialogMessageArg, Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.FDialogApi.showDialogApi", getCodec());
channel.send(new ArrayList<Object>(Arrays.asList(dialogMessageArg)), channelReply -> {
callback.reply(null);
});
}
public void closeDialogApi(Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.FDialogApi.closeDialogApi", getCodec());
channel.send(null, channelReply -> {
callback.reply(null);
});
}
}
private static class HDialogApiCodec extends StandardMessageCodec {
public static final HDialogApiCodec INSTANCE = new HDialogApiCodec();
private HDialogApiCodec() {}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter.*/
public interface HDialogApi {
void dialogClosed(Result<Void> result);
/** The codec used by HDialogApi. */
static MessageCodec<Object> getCodec() {
return HDialogApiCodec.INSTANCE;
}
/** Sets up an instance of `HDialogApi` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, HDialogApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.HDialogApi.dialogClosed", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
Result<Void> resultCallback = new Result<Void>() {
public void success(Void result) {
wrapped.put("result", null);
reply.reply(wrapped);
}
public void error(Throwable error) {
wrapped.put("error", wrapError(error));
reply.reply(wrapped);
}
};
api.dialogClosed(resultCallback);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
reply.reply(wrapped);
}
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static Map<String, Object> wrapError(Throwable exception) {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("message", exception.toString());
errorMap.put("code", exception.getClass().getSimpleName());
errorMap.put("details", "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
return errorMap;
}
}

View File

@ -1,31 +1,27 @@
package com.yubico.authenticator package com.yubico.authenticator
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.yubico.authenticator.api.Pigeon
import com.yubico.authenticator.logging.Log import com.yubico.authenticator.logging.Log
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CoroutineScope
enum class OperationContext(val value: Long) { class AppContext(messenger: BinaryMessenger, coroutineScope: CoroutineScope, private val appViewModel: MainViewModel) {
Oath(0), Yubikey(1), Invalid(-1); private val channel = MethodChannel(messenger, "android.state.appContext")
companion object {
fun getByValue(value: Long) = values().firstOrNull { it.value == value } ?: Invalid
}
}
class AppContext(messenger: BinaryMessenger) : Pigeon.AppApi {
private var _appContext = MutableLiveData(OperationContext.Oath)
val appContext: LiveData<OperationContext> = _appContext
init { init {
Pigeon.AppApi.setup(messenger, this) channel.setHandler(coroutineScope) { method, args ->
when (method) {
"setContext" -> setContext(args["index"] as Int)
else -> throw NotImplementedError()
}
}
} }
override fun setContext(subPageIndex: Long, result: Pigeon.Result<Void>) { private suspend fun setContext(subPageIndex: Int): String {
_appContext.value = OperationContext.getByValue(subPageIndex) val appContext = OperationContext.getByValue(subPageIndex)
Log.d(TAG, "App context is now $_appContext") appViewModel.setAppContext(appContext)
result.success(null) Log.d(TAG, "App context is now $appContext")
return NULL
} }
companion object { companion object {

View File

@ -0,0 +1,11 @@
package com.yubico.authenticator
import com.yubico.yubikit.core.YubiKeyDevice
/**
* Provides behavior to run when a YubiKey is inserted/tapped for a specific view of the app.
*/
interface AppContextManager {
suspend fun processYubiKey(device: YubiKeyDevice)
fun dispose()
}

View File

@ -0,0 +1,34 @@
package com.yubico.authenticator
import android.content.Context
import android.content.SharedPreferences
class AppPreferences(context: Context) {
companion object {
const val PREFS_FILE = "FlutterSharedPreferences"
const val PREF_NFC_OPEN_APP = "flutter.prefNfcOpenApp"
const val PREF_NFC_BYPASS_TOUCH = "flutter.prefNfcBypassTouch"
const val PREF_NFC_COPY_OTP = "flutter.prefNfcCopyOtp"
const val PREF_CLIP_KBD_LAYOUT = "flutter.prefClipKbdLayout"
const val DEFAULT_CLIP_KBD_LAYOUT = "US"
}
private val prefs: SharedPreferences =
context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)
val openAppOnNfcTap: Boolean
get() = prefs.getBoolean(PREF_NFC_OPEN_APP, true)
val bypassTouchOnNfcTap: Boolean
get() = prefs.getBoolean(PREF_NFC_BYPASS_TOUCH, false)
val copyOtpOnNfcTap: Boolean
get() = prefs.getBoolean(PREF_NFC_COPY_OTP, false)
val clipKbdLayout: String
get() = prefs.getString(
PREF_CLIP_KBD_LAYOUT,
DEFAULT_CLIP_KBD_LAYOUT
)!!
}

View File

@ -0,0 +1,105 @@
package com.yubico.authenticator
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import java.io.Closeable
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
/**
* Observes a LiveData value, sending each change to Flutter via an EventChannel.
*/
inline fun <reified T> LiveData<T>.streamTo(lifecycleOwner: LifecycleOwner, messenger: BinaryMessenger, channelName: String): Closeable {
val channel = EventChannel(messenger, channelName)
var sink: EventChannel.EventSink? = null
channel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
sink = events
events.success(value?.let(jsonSerializer::encodeToString) ?: NULL)
}
override fun onCancel(arguments: Any?) {
sink = null
}
})
val observer = Observer<T> {
sink?.success(it?.let(jsonSerializer::encodeToString) ?: NULL)
}
observe(lifecycleOwner, observer)
return Closeable {
removeObserver(observer)
channel.setStreamHandler(null)
}
}
typealias MethodHandler = suspend (method: String, args: Map<String, Any?>) -> String
/**
* Coroutine-based handing of MethodChannel methods called from Flutter.
*/
fun MethodChannel.setHandler(scope: CoroutineScope, handler: MethodHandler) {
setMethodCallHandler { call, result ->
// N.B. Arguments from Flutter are passed as a Map of basic types. We may want to
// consider JSON encoding if we need to pass more complex structures.
// Return values are always JSON strings.
val args = call.arguments<Map<String, Any?>>() ?: mapOf()
scope.launch {
try {
val response = handler.invoke(call.method, args)
result.success(response)
} catch (notImplemented: NotImplementedError) {
result.notImplemented()
} catch (error: Throwable) {
result.error(
error.javaClass.simpleName,
error.toString(),
"Cause: " + error.cause + ", Stacktrace: " + android.util.Log.getStackTraceString(
error
)
)
}
}
}
}
/**
* Coroutine-based method invocation to call a Flutter method and get a result.
*/
suspend fun MethodChannel.invoke(method: String, args: Any?): Any? =
withContext(Dispatchers.Main) {
suspendCoroutine { continuation ->
invokeMethod(
method,
args,
object : MethodChannel.Result {
override fun success(result: Any?) {
continuation.resume(result)
}
override fun error(
errorCode: String,
errorMessage: String?,
errorDetails: Any?
) {
continuation.resumeWithException(Exception("$errorCode: $errorMessage - $errorDetails"))
}
override fun notImplemented() {
continuation.resumeWithException(NotImplementedError("Method not implemented: $method"))
}
})
}
}

View File

@ -1,55 +1,82 @@
package com.yubico.authenticator package com.yubico.authenticator
import com.yubico.authenticator.api.Pigeon.*
import com.yubico.authenticator.logging.Log
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import kotlinx.coroutines.CoroutineScope import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.*
import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
typealias OnDialogClosed = () -> Unit typealias OnDialogCancelled = suspend () -> Unit
typealias OnDialogCancelled = () -> Unit
class DialogManager(messenger: BinaryMessenger, private var coroutineScope: CoroutineScope) : enum class Icon(val value: String) {
HDialogApi { NFC("nfc"),
SUCCESS("success"),
ERROR("error");
}
private val _fDialogApi = FDialogApi(messenger) class DialogManager(messenger: BinaryMessenger, private val coroutineScope: CoroutineScope) {
private val channel =
MethodChannel(messenger, "com.yubico.authenticator.channel.dialog")
private var onCancelled: OnDialogCancelled? = null private var onCancelled: OnDialogCancelled? = null
init { init {
HDialogApi.setup(messenger, this) channel.setHandler(coroutineScope) { method, _ ->
when (method) {
"cancel" -> dialogClosed()
else -> throw NotImplementedError()
}
}
} }
fun showDialog(message: String, cancelled: OnDialogCancelled?) = fun showDialog(icon: Icon, title: String, description: String, cancelled: OnDialogCancelled?) {
coroutineScope.launch(Dispatchers.Main) {
_fDialogApi.showDialogApi(message) { }
}.also {
onCancelled = cancelled onCancelled = cancelled
}
fun closeDialog(onClosed: OnDialogClosed) {
_fDialogApi.closeDialogApi {
coroutineScope.launch(Dispatchers.Main) {
onClosed()
}
}
}
override fun dialogClosed(result: Result<Void>) {
coroutineScope.launch { coroutineScope.launch {
try { channel.invoke(
onCancelled?.invoke() "show",
result.success(null) Json.encodeToString(
} catch (cause: Throwable) { mapOf(
Log.d(TAG, "Failed to close dialog during User cancel action") "title" to title,
result.error(Exception("Failed to close dialog during User cancel action")) "description" to description,
"icon" to icon.value
)
)
)
} }
} }
suspend fun updateDialogState(
icon: Icon? = null,
title: String? = null,
description: String? = null
) {
channel.invoke(
"state",
Json.encodeToString(
mapOf(
"title" to title,
"description" to description,
"icon" to icon?.value
)
)
)
}
suspend fun closeDialog() {
channel.invoke("close", NULL)
}
private suspend fun dialogClosed(): String {
onCancelled?.let {
onCancelled = null
withContext(Dispatchers.Main) {
it.invoke()
}
}
return NULL
} }
companion object { companion object {
const val TAG = "dialogManager" const val TAG = "dialogManager"
} }
} }

View File

@ -1,7 +1,9 @@
package com.yubico.authenticator.oath package com.yubico.authenticator
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
const val NULL = "null"
val jsonSerializer = Json { val jsonSerializer = Json {
// creates properties for default values // creates properties for default values
encodeDefaults = true encodeDefaults = true

View File

@ -1,5 +1,11 @@
package com.yubico.authenticator package com.yubico.authenticator
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle import android.os.Bundle
import android.view.WindowManager import android.view.WindowManager
import androidx.activity.viewModels import androidx.activity.viewModels
@ -7,63 +13,84 @@ import androidx.lifecycle.lifecycleScope
import com.yubico.authenticator.logging.FlutterLog import com.yubico.authenticator.logging.FlutterLog
import com.yubico.authenticator.logging.Log import com.yubico.authenticator.logging.Log
import com.yubico.authenticator.oath.OathManager import com.yubico.authenticator.oath.OathManager
import com.yubico.authenticator.oath.OathViewModel
import com.yubico.yubikit.android.YubiKitManager import com.yubico.yubikit.android.YubiKitManager
import com.yubico.yubikit.android.transport.nfc.NfcConfiguration import com.yubico.yubikit.android.transport.nfc.NfcConfiguration
import com.yubico.yubikit.android.transport.nfc.NfcNotAvailable import com.yubico.yubikit.android.transport.nfc.NfcNotAvailable
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbConfiguration import com.yubico.yubikit.android.transport.usb.UsbConfiguration
import com.yubico.yubikit.core.Logger import com.yubico.yubikit.core.Logger
import com.yubico.yubikit.core.YubiKeyDevice
import io.flutter.embedding.android.FlutterFragmentActivity import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
import kotlinx.coroutines.Dispatchers import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.io.Closeable
import java.util.concurrent.Executors
import kotlin.properties.Delegates import kotlin.properties.Delegates
class MainActivity : FlutterFragmentActivity() { class MainActivity : FlutterFragmentActivity() {
private val viewModel: MainViewModel by viewModels() private val viewModel: MainViewModel by viewModels()
private val oathViewModel: OathViewModel by viewModels()
private val nfcConfiguration = NfcConfiguration() private val nfcConfiguration = NfcConfiguration()
private var hasNfc by Delegates.notNull<Boolean>() private var hasNfc by Delegates.notNull<Boolean>()
private lateinit var yubikit: YubiKitManager private lateinit var yubikit: YubiKitManager
// receives broadcasts when QR Scanner camera is closed
private val qrScannerCameraClosedBR = QRScannerCameraClosedBR()
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (!BuildConfig.DEBUG) { allowScreenshots(false)
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
yubikit = YubiKitManager(this) yubikit = YubiKitManager(this)
setupYubiKeyDiscovery()
setupYubiKitLogger()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
}
private fun setupYubiKeyDiscovery() {
viewModel.handleYubiKey.observe(this) { viewModel.handleYubiKey.observe(this) {
if (it) { if (it) {
Log.d(TAG, "Starting usb discovery")
yubikit.startUsbDiscovery(UsbConfiguration()) { device -> yubikit.startUsbDiscovery(UsbConfiguration()) { device ->
viewModel.yubiKeyDevice.postValue(device) viewModel.setConnectedYubiKey(device)
device.setOnClosed { viewModel.yubiKeyDevice.postValue(null) } processYubiKey(device)
} }
hasNfc = try { hasNfc = startNfcDiscovery()
yubikit.startNfcDiscovery(nfcConfiguration, this) { device -> } else {
viewModel.yubiKeyDevice.apply { stopNfcDiscovery()
lifecycleScope.launch(Dispatchers.Main) { yubikit.stopUsbDiscovery()
value = device Log.d(TAG, "Stopped usb discovery")
postValue(null)
} }
} }
} }
fun startNfcDiscovery(): Boolean =
try {
Log.d(TAG, "Starting nfc discovery")
yubikit.startNfcDiscovery(nfcConfiguration, this, ::processYubiKey)
true true
} catch (e: NfcNotAvailable) { } catch (e: NfcNotAvailable) {
false false
} }
} else {
yubikit.stopNfcDiscovery(this)
yubikit.stopUsbDiscovery()
}
}
setupYubiKitLogger() private fun stopNfcDiscovery() {
if (hasNfc) {
yubikit.stopNfcDiscovery(this)
Log.d(TAG, "Stopped nfc discovery")
}
} }
private fun setupYubiKitLogger() { private fun setupYubiKitLogger() {
@ -81,10 +108,66 @@ class MainActivity : FlutterFragmentActivity() {
}) })
} }
override fun onStart() {
super.onStart()
registerReceiver(qrScannerCameraClosedBR, QRScannerCameraClosedBR.intentFilter)
}
override fun onStop() {
super.onStop()
unregisterReceiver(qrScannerCameraClosedBR)
}
override fun onPause() {
stopNfcDiscovery()
super.onPause()
}
override fun onResume() {
super.onResume()
// Handle existing tag when launched from NDEF
val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
if(tag != null) {
intent.removeExtra(NfcAdapter.EXTRA_TAG)
val executor = Executors.newSingleThreadExecutor()
val device = NfcYubiKeyDevice(tag, nfcConfiguration.timeout, executor)
lifecycleScope.launch {
try {
contextManager?.processYubiKey(device)
device.remove {
executor.shutdown()
startNfcDiscovery()
}
} catch (e: Throwable) {
Log.e(TAG, "Error processing YubiKey in AppContextManager", e.toString())
}
}
} else {
startNfcDiscovery()
}
}
private fun processYubiKey(device: YubiKeyDevice) {
contextManager?.let {
lifecycleScope.launch {
try {
it.processYubiKey(device)
} catch (e: Throwable) {
Log.e(TAG, "Error processing YubiKey in AppContextManager", e.toString())
}
}
}
}
private var contextManager: AppContextManager? = null
private lateinit var appContext: AppContext private lateinit var appContext: AppContext
private lateinit var oathManager: OathManager
private lateinit var dialogManager: DialogManager private lateinit var dialogManager: DialogManager
private lateinit var appPreferences: AppPreferences
private lateinit var flutterLog: FlutterLog private lateinit var flutterLog: FlutterLog
private lateinit var flutterStreams: List<Closeable>
private lateinit var appMethodChannel: AppMethodChannel
override fun configureFlutterEngine(flutterEngine: FlutterEngine) { override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine) super.configureFlutterEngine(flutterEngine)
@ -92,10 +175,80 @@ class MainActivity : FlutterFragmentActivity() {
val messenger = flutterEngine.dartExecutor.binaryMessenger val messenger = flutterEngine.dartExecutor.binaryMessenger
flutterLog = FlutterLog(messenger) flutterLog = FlutterLog(messenger)
appContext = AppContext(messenger) appContext = AppContext(messenger, this.lifecycleScope, viewModel)
dialogManager = DialogManager(messenger, this.lifecycleScope) dialogManager = DialogManager(messenger, this.lifecycleScope)
appPreferences = AppPreferences(this)
appMethodChannel = AppMethodChannel(messenger)
oathManager = OathManager(this, messenger, appContext, viewModel, dialogManager) flutterStreams = listOf(
viewModel.deviceInfo.streamTo(this, messenger, "android.devices.deviceInfo"),
oathViewModel.sessionState.streamTo(this, messenger, "android.oath.sessionState"),
oathViewModel.credentials.streamTo(this, messenger, "android.oath.credentials"),
)
viewModel.appContext.observe(this) {
contextManager?.dispose()
contextManager = when(it) {
OperationContext.Oath -> OathManager(this, messenger, viewModel, oathViewModel, dialogManager, appPreferences)
else -> null
}
viewModel.connectedYubiKey.value?.let(::processYubiKey)
}
}
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
flutterStreams.forEach { it.close() }
super.cleanUpFlutterEngine(flutterEngine)
}
companion object {
const val TAG = "MainActivity"
const val FLAG_SECURE = WindowManager.LayoutParams.FLAG_SECURE
}
/** We observed that some devices (Pixel 2, OnePlus 6) automatically end NFC discovery
* during the use of device camera when scanning QR codes. To handle NFC events correctly,
* this receiver restarts the YubiKit NFC discovery when the QR Scanner camera is closed.
*/
class QRScannerCameraClosedBR : BroadcastReceiver() {
companion object {
val intentFilter = IntentFilter("com.yubico.authenticator.QRScannerView.CameraClosed")
}
override fun onReceive(context: Context?, intent: Intent?) {
(context as? MainActivity)?.startNfcDiscovery()
}
}
inner class AppMethodChannel(messenger: BinaryMessenger) {
private val methodChannel = MethodChannel(messenger, "app.methods")
init {
methodChannel.setMethodCallHandler { methodCall, result ->
when (methodCall.method) {
"allowScreenshots" -> result.success(
allowScreenshots(
methodCall.arguments as Boolean,
)
)
else -> Log.w(TAG, "Unknown app method: ${methodCall.method}")
}
}
}
}
private fun allowScreenshots(value: Boolean): Boolean {
// Note that FLAG_SECURE is the inverse of allowScreenshots
if (value) {
Log.d(TAG, "Clearing FLAG_SECURE (allow screenshots)")
window.clearFlags(FLAG_SECURE)
} else {
Log.d(TAG, "Setting FLAG_SECURE (disallow screenshots)")
window.setFlags(FLAG_SECURE, FLAG_SECURE)
}
return FLAG_SECURE != (window.attributes.flags and FLAG_SECURE)
} }
} }

View File

@ -3,12 +3,34 @@ package com.yubico.authenticator
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import com.yubico.yubikit.core.YubiKeyDevice import com.yubico.authenticator.device.Info
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
enum class OperationContext(val value: Int) {
Oath(0), Yubikey(1), Invalid(-1);
companion object {
fun getByValue(value: Int) = values().firstOrNull { it.value == value } ?: Invalid
}
}
class MainViewModel : ViewModel() { class MainViewModel : ViewModel() {
private val _handleYubiKey = MutableLiveData(true) private val _handleYubiKey = MutableLiveData(true)
val handleYubiKey: LiveData<Boolean> = _handleYubiKey val handleYubiKey: LiveData<Boolean> = _handleYubiKey
val yubiKeyDevice = MutableLiveData<YubiKeyDevice?>() private var _appContext = MutableLiveData(OperationContext.Oath)
val appContext: LiveData<OperationContext> = _appContext
fun setAppContext(appContext: OperationContext) = _appContext.postValue(appContext)
private val _connectedYubiKey = MutableLiveData<UsbYubiKeyDevice?>()
val connectedYubiKey: LiveData<UsbYubiKeyDevice?> = _connectedYubiKey
fun setConnectedYubiKey(device: UsbYubiKeyDevice) {
_connectedYubiKey.postValue(device)
device.setOnClosed { _connectedYubiKey.postValue(null) }
}
private val _deviceInfo = MutableLiveData<Info?>()
val deviceInfo: LiveData<Info?> = _deviceInfo
fun setDeviceInfo(info: Info?) = _deviceInfo.postValue(info)
} }

View File

@ -0,0 +1,117 @@
package com.yubico.authenticator
import android.app.Activity
import android.content.*
import android.nfc.NdefMessage
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import com.yubico.authenticator.logging.Log
import com.yubico.authenticator.yubiclip.scancode.KeyboardLayout
import com.yubico.yubikit.core.util.NdefUtils
import java.nio.charset.StandardCharsets
typealias ResourceId = Int
class NdefActivity : Activity() {
private lateinit var appPreferences: AppPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appPreferences = AppPreferences(this)
handleIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
override fun onPause() {
super.onPause()
overridePendingTransition(0, 0)
}
private fun handleIntent(intent: Intent) {
intent.data?.let {
if (appPreferences.copyOtpOnNfcTap) {
try {
val otpSlotContent = parseOtpFromIntent()
setPrimaryClip(otpSlotContent.content)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) {
showToast(
when (otpSlotContent.type) {
OtpType.Otp -> R.string.otp_success_set_otp_to_clipboard
OtpType.Password -> R.string.otp_success_set_password_to_clipboard
}, Toast.LENGTH_SHORT
)
}
} catch (illegalArgumentException: IllegalArgumentException) {
Log.e(
TAG,
illegalArgumentException.message ?: "Failure when handling YubiKey OTP",
illegalArgumentException.stackTraceToString()
)
showToast(R.string.otp_parse_failure, Toast.LENGTH_LONG)
} catch (_: UnsupportedOperationException) {
showToast(R.string.otp_set_clip_failure, Toast.LENGTH_LONG)
}
}
if (appPreferences.openAppOnNfcTap) {
val mainAppIntent = Intent(this, MainActivity::class.java).apply {
// Pass the NFC Tag to the main Activity.
putExtra(NfcAdapter.EXTRA_TAG, intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG))
}
startActivity(mainAppIntent)
}
finishAndRemoveTask()
}
}
private fun showToast(value: ResourceId, length: Int) {
Toast.makeText(this, value, length).show()
}
private fun parseOtpFromIntent(): OtpSlotValue {
val parcelable = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
if (parcelable != null && parcelable.isNotEmpty()) {
val ndefPayloadBytes =
NdefUtils.getNdefPayloadBytes((parcelable[0] as NdefMessage).toByteArray())
return if (ndefPayloadBytes.all { it in 32..126 }) {
OtpSlotValue(OtpType.Otp, String(ndefPayloadBytes, StandardCharsets.US_ASCII))
} else {
val kbd: KeyboardLayout = KeyboardLayout.forName(appPreferences.clipKbdLayout)
OtpSlotValue(OtpType.Password, kbd.fromScanCodes(ndefPayloadBytes))
}
}
throw IllegalArgumentException("Failed to parse OTP from the intent")
}
private fun setPrimaryClip(otp: String) {
try {
val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText(otp, otp))
} catch (e: Exception) {
Log.e(TAG, "Failed to copy otp string to clipboard", e.stackTraceToString())
throw UnsupportedOperationException()
}
}
companion object {
const val TAG = "YubicoAuthenticatorOTPActivity"
}
enum class OtpType {
Otp, Password
}
data class OtpSlotValue(val type: OtpType, val content: String)
}

View File

@ -4,10 +4,10 @@ import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel
class FlutterLog(messenger: BinaryMessenger) { class FlutterLog(messenger: BinaryMessenger) {
private var _channel = MethodChannel(messenger, "android.log.redirect") private var channel = MethodChannel(messenger, "android.log.redirect")
init { init {
_channel.setMethodCallHandler { call, result -> channel.setMethodCallHandler { call, result ->
when (call.method) { when (call.method) {
"log" -> { "log" -> {

View File

@ -13,11 +13,11 @@ object Log {
ERROR ERROR
} }
const val MAX_BUFFER_SIZE = 1000 private const val MAX_BUFFER_SIZE = 1000
private val _buffer = arrayListOf<String>() private val buffer = arrayListOf<String>()
fun getBuffer() : List<String> { fun getBuffer() : List<String> {
return _buffer return buffer
} }
private var level = if (BuildConfig.DEBUG) { private var level = if (BuildConfig.DEBUG) {
@ -59,12 +59,12 @@ object Log {
return return
} }
if (_buffer.size > MAX_BUFFER_SIZE) { if (buffer.size > MAX_BUFFER_SIZE) {
_buffer.removeAt(0) buffer.removeAt(0)
} }
val logMessage = "[$loggerName] ${level.name}: $message".also { val logMessage = "[$loggerName] ${level.name}: $message".also {
_buffer.add(it) buffer.add(it)
} }
when (level) { when (level) {
@ -76,8 +76,8 @@ object Log {
} }
error?.let { error?.let {
Log.e(TAG, "[$loggerName] ${level.name}: $error".also { Log.e(TAG, "[$loggerName] ${level.name}(details): $error".also {
_buffer.add(it) buffer.add(it)
}) })
} }
} }

View File

@ -1,7 +1,9 @@
package com.yubico.authenticator.oath package com.yubico.authenticator.oath
import com.yubico.authenticator.device.Version
import com.yubico.yubikit.oath.Code import com.yubico.yubikit.oath.Code
import com.yubico.yubikit.oath.Credential import com.yubico.yubikit.oath.Credential
import com.yubico.yubikit.oath.OathSession
import com.yubico.yubikit.oath.OathType import com.yubico.yubikit.oath.OathType
fun ByteArray.asString() = joinToString( fun ByteArray.asString() = joinToString(
@ -9,6 +11,18 @@ fun ByteArray.asString() = joinToString(
) { b -> "%02x".format(b) } ) { b -> "%02x".format(b) }
// convert yubikit types to Model types // convert yubikit types to Model types
fun OathSession.model(isRemembered: Boolean) = Model.Session(
deviceId,
Version(
version.major,
version.minor,
version.micro
),
isAccessKeySet,
isRemembered,
isLocked
)
fun Credential.model(deviceId: String) = Model.Credential( fun Credential.model(deviceId: String) = Model.Credential(
deviceId = deviceId, deviceId = deviceId,
id = id.asString(), id = id.asString(),

View File

@ -8,10 +8,6 @@ import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.encoding.Encoder
fun Model.Credential.isInteractive(): Boolean {
return oathType == Model.OathType.HOTP || (oathType == Model.OathType.TOTP && touchRequired)
}
class Model { class Model {
@Serializable @Serializable
@ -28,6 +24,7 @@ class Model {
val isLocked: Boolean val isLocked: Boolean
) { ) {
@SerialName("keystore") @SerialName("keystore")
@Suppress("unused")
val keystoreState: String = "unknown" val keystoreState: String = "unknown"
} }
@ -63,7 +60,7 @@ class Model {
@Serializable @Serializable
class Code( data class Code(
val value: String? = null, val value: String? = null,
@SerialName("valid_from") @SerialName("valid_from")
@Suppress("unused") @Suppress("unused")
@ -95,96 +92,4 @@ class Model {
} }
} }
private var _credentials = mutableMapOf<Credential, Code?>()
var session : Session? = null
val credentials: List<CredentialWithCode>
get() = _credentials.map {
CredentialWithCode(it.key, it.value)
}
// resets the model to initial values
// used when a usb key has been disconnected
fun reset() {
this._credentials.clear()
this.session = null
}
fun update(deviceId: String, credentials: Map<Credential, Code?>) {
// is the model already holding credentials for the deviceId
val sameDevice = this._credentials.keys.firstOrNull()?.deviceId == deviceId
if (!sameDevice) {
// device was changed, we use the new list
this._credentials.clear()
this._credentials.putAll(from = credentials)
} else {
// update codes for non interactive keys
for ((credential, code) in credentials) {
if (!credential.isInteractive() || !this._credentials.contains(credential)) {
this._credentials[credential] = code
}
}
// remove obsolete credentials
this._credentials.filter { entry ->
// get only keys which are not present in the input map
!credentials.contains(entry.key)
}.forEach(action = {
this._credentials.remove(it.key)
})
}
}
fun add(deviceId: String, credential: Credential, code: Code?): CredentialWithCode? {
if (this.session?.deviceId != deviceId) {
return null
}
_credentials[credential] = code
return CredentialWithCode(credential, code)
}
fun rename(
deviceId: String,
oldCredential: Credential,
newCredential: Credential
): Credential? {
if (this.session?.deviceId != deviceId) {
return null
}
if (oldCredential.deviceId != newCredential.deviceId) {
return null
}
if (!_credentials.contains(oldCredential)) {
return null
}
// preserve code
val code = _credentials[oldCredential]
_credentials.remove(oldCredential)
_credentials[newCredential] = code
return newCredential
}
fun updateCode(deviceId: String, credential: Credential, code: Code?): Code? {
if (this.session?.deviceId != deviceId) {
return null
}
if (!_credentials.contains(credential)) {
return null
}
_credentials[credential] = code
return code
}
} }

View File

@ -1,183 +1,294 @@
package com.yubico.authenticator.oath package com.yubico.authenticator.oath
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import com.yubico.authenticator.* import com.yubico.authenticator.*
import com.yubico.authenticator.api.Pigeon.*
import com.yubico.authenticator.device.Version
import com.yubico.authenticator.logging.Log import com.yubico.authenticator.logging.Log
import com.yubico.authenticator.management.model
import com.yubico.authenticator.oath.keystore.ClearingMemProvider import com.yubico.authenticator.oath.keystore.ClearingMemProvider
import com.yubico.authenticator.oath.keystore.KeyStoreProvider import com.yubico.authenticator.oath.keystore.KeyStoreProvider
import com.yubico.authenticator.yubikit.getDeviceInfo import com.yubico.authenticator.yubikit.getDeviceInfo
import com.yubico.authenticator.yubikit.withSmartCardConnection import com.yubico.authenticator.yubikit.withConnection
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.Transport
import com.yubico.yubikit.core.YubiKeyDevice import com.yubico.yubikit.core.YubiKeyDevice
import com.yubico.yubikit.core.YubiKeyType
import com.yubico.yubikit.core.application.ApplicationNotAvailableException
import com.yubico.yubikit.core.smartcard.SmartCardConnection import com.yubico.yubikit.core.smartcard.SmartCardConnection
import com.yubico.yubikit.core.util.Result
import com.yubico.yubikit.oath.* import com.yubico.yubikit.oath.*
import com.yubico.yubikit.support.DeviceUtil
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.URI import java.net.URI
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.suspendCoroutine
typealias OathAction = (Result<OathSession, Exception>) -> Unit
class OathManager( class OathManager(
private val lifecycleOwner: LifecycleOwner, private val lifecycleOwner: LifecycleOwner,
messenger: BinaryMessenger, messenger: BinaryMessenger,
appContext: AppContext,
private val appViewModel: MainViewModel, private val appViewModel: MainViewModel,
private val dialogManager: DialogManager private val oathViewModel: OathViewModel,
) : OathApi { private val dialogManager: DialogManager,
private val appPreferences: AppPreferences,
private val _dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() ) : AppContextManager {
private val coroutineScope = CoroutineScope(SupervisorJob() + _dispatcher)
private val _fOathApi: FOathApi = FOathApi(messenger)
private val _fManagementApi: FManagementApi = FManagementApi(messenger)
private val _memoryKeyProvider = ClearingMemProvider()
private val _keyManager = KeyManager(KeyStoreProvider(), _memoryKeyProvider)
private var _previousNfcDeviceId = ""
private val _pendingYubiKeyAction = MutableLiveData<YubiKeyAction?>()
private val pendingYubiKeyAction: LiveData<YubiKeyAction?> = _pendingYubiKeyAction
private val _model = Model()
init {
OathApi.setup(messenger, this)
appContext.appContext.observe(lifecycleOwner) {
if (it == OperationContext.Oath) {
installObservers()
} else {
uninstallObservers()
}
}
}
companion object { companion object {
const val TAG = "OathManager" const val TAG = "OathManager"
const val NFC_DATA_CLEANUP_DELAY = 30L * 1000; // 30s
} }
private val deviceObserver = private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
Observer<YubiKeyDevice?> { yubiKeyDevice -> private val coroutineScope = CoroutineScope(SupervisorJob() + dispatcher)
if (yubiKeyDevice != null) {
yubikeyAttached(yubiKeyDevice)
} else {
yubikeyDetached()
}
}
private fun installObservers() { private val oathChannel = MethodChannel(messenger, "android.oath.methods")
Log.d(TAG, "Installed oath observers")
appViewModel.yubiKeyDevice.observe(lifecycleOwner, deviceObserver)
}
private fun uninstallObservers() { private val memoryKeyProvider = ClearingMemProvider()
appViewModel.yubiKeyDevice.removeObserver(deviceObserver) private val keyManager = KeyManager(KeyStoreProvider(), memoryKeyProvider)
Log.d(TAG, "Uninstalled oath observers")
}
private suspend fun provideYubiKey(result: com.yubico.yubikit.core.util.Result<YubiKeyDevice, Exception>) = private var pendingAction: OathAction? = null
pendingYubiKeyAction.value?.let { private var refreshJob: Job? = null
_pendingYubiKeyAction.postValue(null)
it.action.invoke(result)
} ?: run {
Log.e(TAG, "The pending action is not valid anymore")
throw IllegalStateException("The pending action is not valid anymore")
}
private var _isUsbKey = false // provides actions for lifecycle events
private fun yubikeyAttached(device: YubiKeyDevice) { private val lifecycleObserver = object : DefaultLifecycleObserver {
Log.d(TAG, "Device connected")
_isUsbKey = device is UsbYubiKeyDevice private var startTimeMs: Long = -1
val handler = CoroutineExceptionHandler { _, throwable -> override fun onPause(owner: LifecycleOwner) {
Log.e(TAG, "Exception caught: ${throwable.message}") startTimeMs = currentTimeMs
}
coroutineScope.launch(handler) { // cancel any pending actions
sendDeviceInfo(device) pendingAction?.let {
readOathData(device) Log.d(TAG, "Cancelling pending action/closing nfc dialog.")
if (pendingYubiKeyAction.value != null) { it.invoke(Result.failure(CancellationException()))
provideYubiKey(com.yubico.yubikit.core.util.Result.success(device))
} else {
sendOathInfo()
sendOathCodes()
}
}
}
private fun yubikeyDetached() {
if (_isUsbKey) {
Log.d(TAG, "Device disconnected")
// clear keys from memory
_memoryKeyProvider.clearAll()
_pendingYubiKeyAction.postValue(null)
_fManagementApi.updateDeviceInfo("") {}
_model.reset()
}
}
override fun reset(result: Result<Void>) {
coroutineScope.launch { coroutineScope.launch {
dialogManager.closeDialog()
}
pendingAction = null
}
super.onPause(owner)
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
if (canInvoke) {
if (appViewModel.connectedYubiKey.value == null) {
// no USB YubiKey is connected, reset known data on resume
Log.d(TAG, "Removing NFC data after resume.")
appViewModel.setDeviceInfo(null)
oathViewModel.setSessionState(null)
}
}
}
private val currentTimeMs
get() = System.currentTimeMillis()
private val canInvoke: Boolean
get() = startTimeMs != -1L && currentTimeMs - startTimeMs > NFC_DATA_CLEANUP_DELAY
}
private val usbObserver = Observer<UsbYubiKeyDevice?> {
refreshJob?.cancel()
if (it == null) {
appViewModel.setDeviceInfo(null)
oathViewModel.setSessionState(null)
}
}
private val credentialObserver = Observer<List<Model.CredentialWithCode>?> { codes ->
refreshJob?.cancel()
if (codes != null && appViewModel.connectedYubiKey.value != null) {
val expirations = codes
.filter { it.credential.oathType == Model.OathType.TOTP && !it.credential.touchRequired }
.mapNotNull { it.code?.validTo }
if (expirations.isNotEmpty()) {
val earliest = expirations.min() * 1000
val now = System.currentTimeMillis()
refreshJob = coroutineScope.launch {
if (earliest > now) {
delay(earliest - now)
}
requestRefresh()
}
}
}
}
init {
appViewModel.connectedYubiKey.observe(lifecycleOwner, usbObserver)
oathViewModel.credentials.observe(lifecycleOwner, credentialObserver)
// OATH methods callable from Flutter:
oathChannel.setHandler(coroutineScope) { method, args ->
when (method) {
"reset" -> reset()
"unlock" -> unlock(
args["password"] as String,
args["remember"] as Boolean
)
"setPassword" -> setPassword(
args["current"] as String?,
args["password"] as String
)
"unsetPassword" -> unsetPassword(args["current"] as String)
"forgetPassword" -> forgetPassword()
"calculate" -> calculate(args["credentialId"] as String)
"addAccount" -> addAccount(
args["uri"] as String,
args["requireTouch"] as Boolean
)
"renameAccount" -> renameAccount(
args["credentialId"] as String,
args["name"] as String,
args["issuer"] as String?
)
"deleteAccount" -> deleteAccount(args["credentialId"] as String)
else -> throw NotImplementedError()
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
}
override fun dispose() {
lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
appViewModel.connectedYubiKey.removeObserver(usbObserver)
oathViewModel.credentials.removeObserver(credentialObserver)
oathChannel.setMethodCallHandler(null)
coroutineScope.cancel()
}
override suspend fun processYubiKey(device: YubiKeyDevice) {
try { try {
useOathSession("Reset YubiKey", true) { device.withConnection<SmartCardConnection, Unit> { connection ->
val oath = OathSession(connection)
tryToUnlockOathSession(oath)
val previousId = oathViewModel.sessionState.value?.deviceId
if (oath.deviceId == previousId) {
// Run any pending action
pendingAction?.let { action ->
action.invoke(Result.success(oath))
pendingAction = null
}
// Refresh codes
if (!oath.isLocked) {
try {
oathViewModel.updateCredentials(
calculateOathCodes(oath).model(oath.deviceId)
)
} catch (error: Exception) {
Log.e(TAG, "Failed to refresh codes", error.toString())
}
}
} else {
// Awaiting an action for a different device? Fail it and stop processing.
pendingAction?.let { action ->
action.invoke(Result.failure(IllegalStateException("Wrong deviceId")))
pendingAction = null
return@withConnection
}
// Clear in-memory password for any previous device
if (connection.transport == Transport.NFC && previousId != null) {
memoryKeyProvider.removeKey(previousId)
}
// Update the OATH state
oathViewModel.setSessionState(oath.model(keyManager.isRemembered(oath.deviceId)))
if (!oath.isLocked) {
oathViewModel.updateCredentials(
calculateOathCodes(oath).model(oath.deviceId)
)
}
// Update deviceInfo since the deviceId has changed
if (oath.version.isLessThan(4, 0, 0) && connection.transport == Transport.NFC) {
// NEO over NFC, need a new connection to select another applet
device.requestConnection(SmartCardConnection::class.java) {
try {
val deviceInfo = DeviceUtil.readInfo(it.value, null)
appViewModel.setDeviceInfo(
deviceInfo.model(
DeviceUtil.getName(deviceInfo, YubiKeyType.NEO),
true,
null
)
)
} catch (e: Exception) {
Log.e(TAG, "Failed to read device info", e.toString())
}
}
} else {
// Not a NEO over NFC, reuse existing connection
val pid = (device as? UsbYubiKeyDevice)?.pid
val deviceInfo = DeviceUtil.readInfo(connection, pid)
appViewModel.setDeviceInfo(
deviceInfo.model(
DeviceUtil.getName(deviceInfo, pid?.type),
device.transport == Transport.NFC,
pid?.value
)
)
}
}
}
Log.d(
TAG,
"Successfully read Oath session info (and credentials if unlocked) from connected key"
)
} catch (e: Exception) {
// OATH not enabled/supported, try to get DeviceInfo over other USB interfaces
Log.e(TAG, "Failed to connect to CCID", e.toString())
if (device.transport == Transport.USB || e is ApplicationNotAvailableException) {
val deviceInfoData = getDeviceInfo(device)
Log.d(TAG, "Sending device info: $deviceInfoData")
appViewModel.setDeviceInfo(deviceInfoData)
}
// Clear any cached OATH state
oathViewModel.setSessionState(null)
}
}
private suspend fun reset(): String {
useOathSession("Reset YubiKey") {
// note, it is ok to reset locked session // note, it is ok to reset locked session
it.reset() it.reset()
_keyManager.removeKey(it.deviceId) keyManager.removeKey(it.deviceId)
returnSuccess(result) oathViewModel.setSessionState(it.model(false))
}
} catch (e: Throwable) {
returnError(result, e)
}
} }
return NULL
} }
override fun unlock( private suspend fun unlock(password: String, remember: Boolean): String =
password: String, useOathSession("Unlocking") {
remember: Boolean,
result: Result<UnlockResponse>
) {
coroutineScope.launch {
try {
useOathSession("Unlocking", true) {
val accessKey = it.deriveAccessKey(password.toCharArray()) val accessKey = it.deriveAccessKey(password.toCharArray())
_keyManager.addKey(it.deviceId, accessKey, remember) keyManager.addKey(it.deviceId, accessKey, remember)
val response = UnlockResponse().apply { val unlocked = tryToUnlockOathSession(it)
isUnlocked = tryToUnlockOathSession(it) val remembered = keyManager.isRemembered(it.deviceId)
isRemembered = _keyManager.isRemembered(it.deviceId) if (unlocked) {
} oathViewModel.setSessionState(it.model(remembered))
if (response.isUnlocked == true) { oathViewModel.updateCredentials(calculateOathCodes(it).model(it.deviceId))
_model.update(it.deviceId, calculateOathCodes(it).model(it.deviceId))
coroutineScope.launch {
sendOathCodes()
}
}
returnSuccess(result, response)
} }
} catch (cause: Throwable) { jsonSerializer.encodeToString(mapOf("unlocked" to unlocked, "remembered" to remembered))
returnError(result, cause)
}
}
} }
override fun setPassword( private suspend fun setPassword(
currentPassword: String?, currentPassword: String?,
newPassword: String, newPassword: String,
result: Result<Void> ): String =
) { useOathSession("Set password") { session ->
coroutineScope.launch {
try {
useOathSession("Set password", true) { session ->
if (session.isAccessKeySet) { if (session.isAccessKeySet) {
if (currentPassword == null) { if (currentPassword == null) {
throw Exception("Must provide current password to be able to change it") throw Exception("Must provide current password to be able to change it")
@ -189,53 +300,46 @@ class OathManager(
} }
val accessKey = session.deriveAccessKey(newPassword.toCharArray()) val accessKey = session.deriveAccessKey(newPassword.toCharArray())
session.setAccessKey(accessKey) session.setAccessKey(accessKey)
_keyManager.addKey(session.deviceId, accessKey, false) keyManager.addKey(session.deviceId, accessKey, false)
oathViewModel.setSessionState(session.model(false))
Log.d(TAG, "Successfully set password") Log.d(TAG, "Successfully set password")
returnSuccess(result) NULL
}
} catch (cause: Throwable) {
returnError(result, cause)
}
}
} }
override fun unsetPassword(currentPassword: String, result: Result<Void>) { private suspend fun unsetPassword(currentPassword: String): String =
coroutineScope.launch { useOathSession("Unset password") { session ->
try {
useOathSession("Unset password", true) { session ->
if (session.isAccessKeySet) { if (session.isAccessKeySet) {
// test current password sent by the user // test current password sent by the user
if (session.unlock(currentPassword.toCharArray())) { if (session.unlock(currentPassword.toCharArray())) {
session.deleteAccessKey() session.deleteAccessKey()
_keyManager.removeKey(session.deviceId) keyManager.removeKey(session.deviceId)
oathViewModel.setSessionState(session.model(false))
Log.d(TAG, "Successfully unset password") Log.d(TAG, "Successfully unset password")
returnSuccess(result) return@useOathSession NULL
return@useOathSession
}
}
returnError(result, Exception("Unset password failed"))
}
} catch (cause: Throwable) {
returnError(result, cause)
} }
} }
throw Exception("Unset password failed")
} }
override fun forgetPassword(result: Result<Void>) { private suspend fun forgetPassword(): String {
_keyManager.clearAll() keyManager.clearAll()
Log.d(TAG, "Cleared all keys.") Log.d(TAG, "Cleared all keys.")
returnSuccess(result) oathViewModel.sessionState.value?.let {
oathViewModel.setSessionState(
it.copy(
isLocked = it.isAccessKeySet,
isRemembered = false
)
)
}
return NULL
} }
override fun addAccount( private suspend fun addAccount(
uri: String, uri: String,
requireTouch: Boolean, requireTouch: Boolean,
result: Result<String> ): String =
) { useOathSession("Add account") { session ->
coroutineScope.launch {
try {
useOathSession("Add account", true) { session ->
withUnlockedSession(session) {
val credentialData: CredentialData = val credentialData: CredentialData =
CredentialData.parseUri(URI.create(uri)) CredentialData.parseUri(URI.create(uri))
@ -247,121 +351,57 @@ class OathManager(
calculateCode(session, credential) calculateCode(session, credential)
} else null } else null
val addedCred = _model.add( val addedCred = oathViewModel.addCredential(
session.deviceId,
credential.model(session.deviceId), credential.model(session.deviceId),
code?.model() code?.model()
) )
if (addedCred != null) { jsonSerializer.encodeToString(addedCred)
val jsonResult = jsonSerializer.encodeToString(addedCred)
returnSuccess(result, jsonResult)
} else {
// TODO - figure out better error handling here
returnError(result, java.lang.IllegalStateException())
}
}
}
} catch (cause: Throwable) {
returnError(result, cause)
}
}
} }
override fun renameAccount(uri: String, name: String, issuer: String?, result: Result<String>) { private suspend fun renameAccount(uri: String, name: String, issuer: String?): String =
coroutineScope.launch { useOathSession("Rename") { session ->
try {
useOathSession("Rename", true) { session ->
withUnlockedSession(session) {
val credential = getOathCredential(session, uri) val credential = getOathCredential(session, uri)
val renamedCredential =
val renamedCredential = _model.rename( session.renameCredential(credential, name, issuer).model(session.deviceId)
it.deviceId, oathViewModel.renameCredential(
credential.model(it.deviceId), credential.model(session.deviceId),
session.renameCredential(credential, name, issuer).model(it.deviceId) renamedCredential
) )
if (renamedCredential != null) {
val jsonResult =
jsonSerializer.encodeToString(renamedCredential) jsonSerializer.encodeToString(renamedCredential)
returnSuccess(result, jsonResult)
} else {
// TODO - figure out better error handling here
returnError(result, java.lang.IllegalStateException())
}
}
}
} catch (cause: Throwable) {
returnError(result, cause)
}
}
} }
override fun deleteAccount(uri: String, result: Result<Void>) { private suspend fun deleteAccount(credentialId: String): String =
coroutineScope.launch { useOathSession("Delete account") { session ->
useOathSession("Delete account", true) { session -> val credential = getOathCredential(session, credentialId)
withUnlockedSession(session) {
val credential = getOathCredential(session, uri)
session.deleteCredential(credential) session.deleteCredential(credential)
returnSuccess(result) oathViewModel.removeCredential(credential.model(session.deviceId))
} NULL
}
}
} }
override fun refreshCodes(result: Result<String>) { private suspend fun requestRefresh() {
coroutineScope.launch { appViewModel.connectedYubiKey.value?.let { usbYubiKeyDevice ->
try { useOathSessionUsb(usbYubiKeyDevice) { session ->
if (!_isUsbKey) { oathViewModel.updateCredentials(
throw Exception("Cannot refresh for nfc key")
}
useOathSession("Refresh codes", false) {
withUnlockedSession(it) { session ->
_model.update(
session.deviceId,
calculateOathCodes(session).model(session.deviceId) calculateOathCodes(session).model(session.deviceId)
) )
val resultJson = jsonSerializer.encodeToString(_model.credentials)
returnSuccess(result, resultJson)
}
}
} catch (cause: Throwable) {
returnError(result, cause)
}
} }
} ?: throw IllegalStateException("Cannot refresh for nfc key")
} }
override fun calculate(uri: String, result: Result<String>) { private suspend fun calculate(credentialId: String): String =
coroutineScope.launch { useOathSession("Calculate") { session ->
try { val credential = getOathCredential(session, credentialId)
useOathSession("Calculate", true) {
withUnlockedSession(it) { session ->
val credential = getOathCredential(session, uri) val code = calculateCode(session, credential).model()
oathViewModel.updateCode(
val code = _model.updateCode(
session.deviceId,
credential.model(session.deviceId), credential.model(session.deviceId),
calculateCode(session, credential).model() code
) )
Log.d(TAG, "Code calculated $code")
if (code != null) { jsonSerializer.encodeToString(code)
val resultJson = jsonSerializer.encodeToString(code)
returnSuccess(result, resultJson)
} else {
// TODO - figure out better error handling here
returnError(result, java.lang.IllegalStateException())
}
}
}
} catch (cause: Throwable) {
returnError(result, cause)
}
}
} }
/** /**
@ -384,85 +424,11 @@ class OathManager(
} }
} }
private suspend fun sendDeviceInfo(device: YubiKeyDevice) {
val deviceInfoData = getDeviceInfo(device)
withContext(Dispatchers.Main) {
Log.d(TAG, "Sending device info: $deviceInfoData")
_fManagementApi.updateDeviceInfo(Json.encodeToString(deviceInfoData)) {
Log.d(TAG, "Device info sent successfully")
}
}
}
private suspend fun readOathData(device: YubiKeyDevice) {
withSmartCardConnection(device) { smartCardConnection ->
val oathSession = OathSession(smartCardConnection)
val deviceId = oathSession.deviceId
_previousNfcDeviceId = if (device is NfcYubiKeyDevice) {
if (deviceId != _previousNfcDeviceId) {
// devices are different, clear access key for previous device
_memoryKeyProvider.removeKey(_previousNfcDeviceId)
}
deviceId
} else {
""
}
// calling unlock session will remove invalid access keys
val isUnlocked = tryToUnlockOathSession(oathSession)
val isRemembered = _keyManager.isRemembered(deviceId)
_model.session = Model.Session(
deviceId,
Version(
oathSession.version.major,
oathSession.version.minor,
oathSession.version.micro
),
oathSession.isAccessKeySet,
isRemembered,
oathSession.isLocked
)
if (isUnlocked) {
_model.update(
deviceId,
calculateOathCodes(oathSession).model(deviceId)
)
}
Log.d(TAG, "Successfully read Oath session info (and credentials if unlocked) from connected key")
}
}
private suspend fun sendOathInfo() {
val oathSessionData = jsonSerializer.encodeToString(_model.session)
withContext(Dispatchers.Main) {
Log.d(TAG, "Sending OathSessionData")
_fOathApi.updateSession(oathSessionData) {
Log.d(TAG, "OathSessionData sent successfully")
}
}
}
private suspend fun sendOathCodes() {
val sendOathCodes = jsonSerializer.encodeToString(_model.credentials)
withContext(Dispatchers.Main) {
Log.d(TAG, "Sending OathCredentials")
_fOathApi.updateOathCredentials(sendOathCodes) {
Log.d(TAG, "OathCredentials sent successfully")
}
}
}
/** /**
* Tries to unlocks [OathSession] with [AccessKey] stored in [KeyManager]. On failure clears * Tries to unlocks [OathSession] with [AccessKey] stored in [KeyManager]. On failure clears
* relevant access keys from [KeyManager] * relevant access keys from [KeyManager]
* *
* @return true if we the session is not locked or it was successfully unlocked, false otherwise * @return true if the session is not locked or it was successfully unlocked, false otherwise
*/ */
private fun tryToUnlockOathSession(session: OathSession): Boolean { private fun tryToUnlockOathSession(session: OathSession): Boolean {
if (!session.isLocked) { if (!session.isLocked) {
@ -470,7 +436,7 @@ class OathManager(
} }
val deviceId = session.deviceId val deviceId = session.deviceId
val accessKey = _keyManager.getKey(deviceId) val accessKey = keyManager.getKey(deviceId)
?: return false // we have no access key to unlock the session ?: return false // we have no access key to unlock the session
val unlockSucceed = session.unlock(accessKey) val unlockSucceed = session.unlock(accessKey)
@ -479,20 +445,25 @@ class OathManager(
return true return true
} }
_keyManager.removeKey(deviceId) // remove invalid access keys from [KeyManager] keyManager.removeKey(deviceId) // remove invalid access keys from [KeyManager]
return false // the unlock did not work, session is locked return false // the unlock did not work, session is locked
} }
private fun calculateOathCodes(session: OathSession): Map<Credential, Code> { private fun calculateOathCodes(session: OathSession): Map<Credential, Code> {
val isUsbKey = appViewModel.connectedYubiKey.value != null
var timestamp = System.currentTimeMillis() var timestamp = System.currentTimeMillis()
if (!_isUsbKey) { if (!isUsbKey) {
// NFC, need to pad timer to avoid immediate expiration // NFC, need to pad timer to avoid immediate expiration
timestamp += 10000 timestamp += 10000
} }
val bypassTouch = appPreferences.bypassTouchOnNfcTap && !isUsbKey
return session.calculateCodes(timestamp).map { (credential, code) -> return session.calculateCodes(timestamp).map { (credential, code) ->
Pair( Pair(
credential, if (credential.isSteamCredential() && !credential.isTouchRequired) { credential,
if (credential.isSteamCredential() && (!credential.isTouchRequired || bypassTouch)) {
session.calculateSteamCode(credential, timestamp) session.calculateSteamCode(credential, timestamp)
} else if (credential.isTouchRequired && bypassTouch) {
session.calculateCode(credential, timestamp)
} else { } else {
code code
} }
@ -500,83 +471,69 @@ class OathManager(
}.toMap() }.toMap()
} }
private fun <T> withUnlockedSession(session: OathSession, block: (OathSession) -> T): T {
if (!tryToUnlockOathSession(session)) {
throw Exception("Session is locked")
}
return block(session)
}
private suspend fun <T> useOathSession( private suspend fun <T> useOathSession(
title: String, title: String,
queryUserToTap: Boolean,
action: (OathSession) -> T action: (OathSession) -> T
) = suspendCoroutine<T> { outer -> ): T {
if (queryUserToTap && !_isUsbKey) { return appViewModel.connectedYubiKey.value?.let {
dialogManager.showDialog(title) { useOathSessionUsb(it, action)
coroutineScope.launch(Dispatchers.Main) { } ?: useOathSessionNfc(title, action)
Log.d(TAG, "Cancelled Dialog $title")
provideYubiKey(com.yubico.yubikit.core.util.Result.failure(Exception("User canceled")))
}
}
} }
if (_isUsbKey) { private suspend fun <T> useOathSessionUsb(
appViewModel.yubiKeyDevice.value?.let { yubiKey -> device: UsbYubiKeyDevice,
Log.d(TAG, "Executing action on usb key: $title") block: (OathSession) -> T
yubiKey.requestConnection(SmartCardConnection::class.java) { ): T = device.withConnection<SmartCardConnection, T> {
action.invoke(OathSession(it.value)) val oath = OathSession(it)
tryToUnlockOathSession(oath)
block(oath)
} }
} ?: run {
Log.e(TAG, "USB Key not found for action: $title") private suspend fun <T> useOathSessionNfc(
throw IllegalStateException("USB Key not found for action: $title") title: String,
} block: (OathSession) -> T
} else { ): T {
_pendingYubiKeyAction.postValue(YubiKeyAction(title) { yubiKey -> try {
val result = suspendCoroutine { outer ->
pendingAction = {
outer.resumeWith(runCatching { outer.resumeWith(runCatching {
suspendCoroutine { inner -> block.invoke(it.value)
yubiKey.value.requestConnection(SmartCardConnection::class.java) {
inner.resumeWith(runCatching {
action.invoke(OathSession(it.value))
}) })
} }
dialogManager.showDialog(Icon.NFC, "Tap your key", title) {
Log.d(TAG, "Cancelled Dialog $title")
pendingAction?.invoke(Result.failure(CancellationException()))
pendingAction = null
} }
}) }
}) dialogManager.updateDialogState(
icon = Icon.SUCCESS,
title = "Success"
)
// TODO: This delays the closing of the dialog, but also the return value
delay(500)
return result
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
dialogManager.updateDialogState(
icon = Icon.ERROR,
title = "Failure",
description = "Action failed - try again"
)
// TODO: This delays the closing of the dialog, but also the return value
delay(1500)
throw error
} finally {
dialogManager.closeDialog()
} }
} }
private fun getOathCredential(oathSession: OathSession, credentialId: String) = private fun getOathCredential(oathSession: OathSession, credentialId: String) =
oathSession.credentials.firstOrNull { credential -> // we need to use oathSession.calculateCodes() to get proper Credential.touchRequired value
oathSession.calculateCodes().map { e -> e.key }.firstOrNull { credential ->
(credential != null) && credential.id.asString() == credentialId (credential != null) && credential.id.asString() == credentialId
} ?: throw Exception("Failed to find account to delete") } ?: throw Exception("Failed to find account")
/// for nfc connection waits for the dialog to be closed and then returns success data
/// for usb connection returns success data directly
private fun <T> returnSuccess(result: Result<T>, data: T? = null) {
coroutineScope.launch(Dispatchers.Main) {
if (!_isUsbKey) {
dialogManager.closeDialog {
result.success(data)
}
} else {
result.success(data)
}
}
}
/// for nfc connection waits for the dialog to be closed and then returns error
/// for usb connection returns error directly
private fun <T> returnError(result: Result<T>, error: Throwable) {
coroutineScope.launch(Dispatchers.Main) {
if (!_isUsbKey) {
dialogManager.closeDialog {
result.error(error)
}
} else {
result.error(error)
}
}
}
} }

View File

@ -0,0 +1,66 @@
package com.yubico.authenticator.oath
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class OathViewModel: ViewModel() {
private val _sessionState = MutableLiveData<Model.Session?>()
val sessionState: LiveData<Model.Session?> = _sessionState
fun setSessionState(sessionState: Model.Session?) {
val oldDeviceId = _sessionState.value?.deviceId
_sessionState.postValue(sessionState)
if(oldDeviceId != sessionState?.deviceId) {
_credentials.postValue(null)
}
}
private val _credentials = MutableLiveData<List<Model.CredentialWithCode>?>()
val credentials: LiveData<List<Model.CredentialWithCode>?> = _credentials
fun updateCredentials(credentials: Map<Model.Credential, Model.Code?>): List<Model.CredentialWithCode> {
val existing = _credentials.value?.associate { it.credential to it.code } ?: mapOf()
val updated = credentials.map {
Model.CredentialWithCode(it.key, it.value ?: existing[it.key])
}
_credentials.postValue(updated)
return updated
}
fun addCredential(credential: Model.Credential, code: Model.Code?): Model.CredentialWithCode {
if(credential.deviceId != _sessionState.value?.deviceId) {
throw IllegalArgumentException("Cannot add credential for different deviceId")
}
return Model.CredentialWithCode(credential, code).also {
_credentials.postValue(_credentials.value?.plus(it))
}
}
fun renameCredential(
oldCredential: Model.Credential,
newCredential: Model.Credential
) {
val existing = _credentials.value!!
val entry = existing.find { it.credential == oldCredential }!!
if(entry.credential.deviceId != newCredential.deviceId) {
throw IllegalArgumentException("Cannot rename credential for different deviceId")
}
_credentials.postValue(existing.minus(entry).plus(Model.CredentialWithCode(newCredential, entry.code)))
}
fun removeCredential(credential: Model.Credential) {
val existing = _credentials.value!!
val entry = existing.find { it.credential == credential }!!
_credentials.postValue(existing.minus(entry))
}
fun updateCode(credential: Model.Credential, code: Model.Code?) {
val existing = _credentials.value!!
val entry = existing.find { it.credential == credential }!!
_credentials.postValue(existing.minus(entry).plus(Model.CredentialWithCode(credential, code)))
}
}

View File

@ -14,7 +14,7 @@ class KeyStoreProvider : KeyProvider {
keystore.load(null) keystore.load(null)
} }
override fun hasKey(deviceId: String): Boolean = keystore.containsAlias(deviceId) override fun hasKey(deviceId: String): Boolean = keystore.containsAlias(getAlias(deviceId))
override fun getKey(deviceId: String): AccessKey? = override fun getKey(deviceId: String): AccessKey? =
if (hasKey(deviceId)) { if (hasKey(deviceId)) {
@ -25,7 +25,7 @@ class KeyStoreProvider : KeyProvider {
override fun putKey(deviceId: String, secret: ByteArray) { override fun putKey(deviceId: String, secret: ByteArray) {
keystore.setEntry( keystore.setEntry(
deviceId, getAlias(deviceId),
KeyStore.SecretKeyEntry( KeyStore.SecretKeyEntry(
SecretKeySpec(secret, KeyProperties.KEY_ALGORITHM_HMAC_SHA1) SecretKeySpec(secret, KeyProperties.KEY_ALGORITHM_HMAC_SHA1)
), ),
@ -35,7 +35,7 @@ class KeyStoreProvider : KeyProvider {
override fun removeKey(deviceId: String) { override fun removeKey(deviceId: String) {
keystore.deleteEntry(deviceId) keystore.deleteEntry(getAlias(deviceId))
} }
override fun clearAll() { override fun clearAll() {
@ -45,9 +45,13 @@ class KeyStoreProvider : KeyProvider {
private inner class KeyStoreStoredSigner(val deviceId: String) : private inner class KeyStoreStoredSigner(val deviceId: String) :
AccessKey { AccessKey {
val mac: Mac = Mac.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA1).apply { val mac: Mac = Mac.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA1).apply {
init(keystore.getKey(deviceId, null)) init(keystore.getKey(getAlias(deviceId), null))
} }
override fun calculateResponse(challenge: ByteArray): ByteArray = mac.doFinal(challenge) override fun calculateResponse(challenge: ByteArray): ByteArray = mac.doFinal(challenge)
} }
// return key alias used in legacy app
private fun getAlias(deviceId: String) = "$deviceId,0"
} }

View File

@ -0,0 +1,141 @@
package com.yubico.authenticator.yubiclip.scancode;
/**
* Created by mjenny on 7/12/15.
*/
public class DECHKeyboardLayout extends KeyboardLayout {
private static final String[] usb2key1 = new String[]{
"",
"",
"",
"",
"a",
"b",
"c",
"d",
"e",
"f",
"g", /* 0xa */
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q", /* 0x14 */
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"z",
"y",
"1", /* 0x1e */
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"\n", /* 0x28 */
"",
"",
"\t",
" ",
"'",
"^",
"ü",
"¨",
"",
"$",
"ö",
"ä",
"§",
",",
".",
"-", /* 0x38 */
};
private static final String[] usb2key2 = new String[]{
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G", /* 0x8a */
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q", /* 0x94 */
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Z",
"Y",
"+",
"\"",
"*",
"ç",
"%",
"&",
"/",
"(",
")",
"=",
"",
"",
"",
"",
"",
"?",
"`",
"è",
"!",
"",
"£",
"Ö",
"Ä",
"°",
";",
":",
"_",
};
@Override
protected String fromScanCode(int code) {
if (code < SHIFT) {
if (code < usb2key1.length) {
return usb2key1[code];
}
} else {
code = code ^ SHIFT;
if (code < usb2key2.length) {
return usb2key2[code];
}
}
return "";
}
}

View File

@ -0,0 +1,141 @@
package com.yubico.authenticator.yubiclip.scancode;
/**
* Created by kemiren on 6/18/14.
*/
public class DEKeyboardLayout extends KeyboardLayout {
private static final String[] usb2key1 = new String[]{
"",
"",
"",
"",
"a",
"b",
"c",
"d",
"e",
"f",
"g", /* 0xa */
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q", /* 0x14 */
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"z",
"y",
"1", /* 0x1e */
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"\n", /* 0x28 */
"",
"",
"\t",
" ",
"ß",
"´",
"ü",
"+",
"",
"#",
"ö",
"'",
"^",
",",
".",
"-", /* 0x38 */
};
private static final String[] usb2key2 = new String[]{
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G", /* 0x8a */
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q", /* 0x94 */
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Z",
"Y",
"!",
"\"",
"§",
"$",
"%",
"&",
"/",
"(",
")",
"=",
"",
"",
"",
"",
"",
"?",
"`",
"Ü",
"*",
"",
">",
"Ö",
"Ä",
"'",
";",
":",
"_",
};
@Override
protected String fromScanCode(int code) {
if (code < SHIFT) {
if (code < usb2key1.length) {
return usb2key1[code];
}
} else {
code = code ^ SHIFT;
if (code < usb2key2.length) {
return usb2key2[code];
}
}
return "";
}
}

View File

@ -0,0 +1,40 @@
package com.yubico.authenticator.yubiclip.scancode;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Created by dain on 2/17/14.
*/
public abstract class KeyboardLayout {
private static final Map<String, KeyboardLayout> layouts = new HashMap<String, KeyboardLayout>();
static {
layouts.put("US", new USKeyboardLayout());
layouts.put("DE", new DEKeyboardLayout());
layouts.put("DE-CH", new DECHKeyboardLayout());
}
public static KeyboardLayout forName(String name) {
return layouts.get(name.toUpperCase());
}
public static Set<String> availableLayouts() {
return new TreeSet<>(layouts.keySet());
}
protected static final int SHIFT = 0x80;
protected abstract String fromScanCode(int code);
public final String fromScanCodes(byte[] bytes) {
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
buf.append(fromScanCode(b & 0xff));
}
return buf.toString();
}
}

View File

@ -0,0 +1,141 @@
package com.yubico.authenticator.yubiclip.scancode;
/**
* Created by dain on 2/17/14.
*/
public class USKeyboardLayout extends KeyboardLayout {
private static final String[] usb2key1 = new String[]{
"",
"",
"",
"",
"a",
"b",
"c",
"d",
"e",
"f",
"g", /* 0xa */
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q", /* 0x14 */
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"1", /* 0x1e */
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"\n", /* 0x28 */
"",
"",
"\t",
" ",
"-",
"=",
"[",
"]",
"",
"\\",
";",
"'",
"`",
",",
".",
"/", /* 0x38 */
};
private static final String[] usb2key2 = new String[]{
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G", /* 0x8a */
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q", /* 0x94 */
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"!",
"@",
"#",
"$",
"%",
"^",
"&",
"*",
"(",
")",
"",
"",
"",
"",
"",
"_",
"+",
"{",
"}",
"",
"|",
":",
"\"",
"~",
"<",
">",
"?",
};
@Override
protected String fromScanCode(int code) {
if (code < SHIFT) {
if (code < usb2key1.length) {
return usb2key1[code];
}
} else {
code = code ^ SHIFT;
if (code < usb2key2.length) {
return usb2key2[code];
}
}
return "";
}
}

View File

@ -1,56 +1,15 @@
package com.yubico.authenticator.yubikit package com.yubico.authenticator.yubikit
import com.yubico.authenticator.device.Info import com.yubico.yubikit.core.YubiKeyConnection
import com.yubico.authenticator.logging.Log
import com.yubico.authenticator.management.model
import com.yubico.authenticator.oath.OathManager
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.YubiKeyDevice import com.yubico.yubikit.core.YubiKeyDevice
import com.yubico.yubikit.core.fido.FidoConnection
import com.yubico.yubikit.core.otp.OtpConnection
import com.yubico.yubikit.core.smartcard.SmartCardConnection
import com.yubico.yubikit.support.DeviceUtil
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.suspendCoroutine
suspend inline fun <reified C : YubiKeyConnection, T> YubiKeyDevice.withConnection(
suspend fun <T> withSmartCardConnection( crossinline block: (C) -> T
device: YubiKeyDevice, ): T = suspendCoroutine { continuation ->
block: (SmartCardConnection) -> T requestConnection(C::class.java) {
) = continuation.resumeWith(runCatching {
suspendCoroutine<T> { continuation -> block(it.value)
device.requestConnection(SmartCardConnection::class.java) { })
if (it.isError) {
continuation.resumeWithException(IllegalStateException("Failed to get SmartCardConnection"))
} else {
continuation.resume(block(it.value))
}
}
}
suspend fun <T> withOTPConnection(device: YubiKeyDevice, block: (OtpConnection) -> T) =
suspendCoroutine<T> { continuation ->
device.requestConnection(OtpConnection::class.java) {
if (it.isError) {
continuation.resumeWithException(IllegalStateException("Failed to get OtpConnection"))
} else {
continuation.resume(block(it.value))
}
}
}
suspend fun <T> withFidoConnection(
device: YubiKeyDevice,
block: (FidoConnection) -> T
) =
suspendCoroutine<T> { continuation ->
device.requestConnection(FidoConnection::class.java) {
if (it.isError) {
continuation.resumeWithException(IllegalStateException("Failed to get FidoConnection"))
} else {
continuation.resume(block(it.value))
}
}
} }
}

View File

@ -7,37 +7,31 @@ import com.yubico.authenticator.oath.OathManager
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.YubiKeyDevice import com.yubico.yubikit.core.YubiKeyDevice
import com.yubico.yubikit.core.fido.FidoConnection
import com.yubico.yubikit.core.otp.OtpConnection
import com.yubico.yubikit.core.smartcard.SmartCardConnection
import com.yubico.yubikit.management.DeviceInfo
import com.yubico.yubikit.support.DeviceUtil import com.yubico.yubikit.support.DeviceUtil
suspend fun getDeviceInfo(device: YubiKeyDevice): Info = suspend fun getDeviceInfo(device: YubiKeyDevice): Info {
try {
withSmartCardConnection(device) {
val pid = (device as? UsbYubiKeyDevice)?.pid val pid = (device as? UsbYubiKeyDevice)?.pid
val deviceInfo = DeviceUtil.readInfo(it, pid)
val name = DeviceUtil.getName(deviceInfo, pid?.type) val deviceInfo = runCatching {
deviceInfo.model(name, device is NfcYubiKeyDevice, pid?.value) device.withConnection<SmartCardConnection, DeviceInfo> { DeviceUtil.readInfo(it, pid) }
} }.recoverCatching {
} catch (exception: Exception) {
Log.d(OathManager.TAG, "Smart card connection not available") Log.d(OathManager.TAG, "Smart card connection not available")
try { device.withConnection<OtpConnection, DeviceInfo> { DeviceUtil.readInfo(it, pid) }
withOTPConnection(device) { }.recoverCatching {
val pid = (device as? UsbYubiKeyDevice)?.pid
val deviceInfo = DeviceUtil.readInfo(it, pid)
val name = DeviceUtil.getName(deviceInfo, pid?.type)
deviceInfo.model(name, device is NfcYubiKeyDevice, pid?.value)
}
} catch (exception: Exception) {
Log.d(OathManager.TAG, "OTP connection not available") Log.d(OathManager.TAG, "OTP connection not available")
try { device.withConnection<FidoConnection, DeviceInfo> { DeviceUtil.readInfo(it, pid) }
withFidoConnection(device) { }.recoverCatching {
val pid = (device as? UsbYubiKeyDevice)?.pid Log.d(OathManager.TAG, "FIDO connection not available")
val deviceInfo = DeviceUtil.readInfo(it, pid) return SkyHelper.getDeviceInfo(device)
}.getOrElse {
Log.e(OathManager.TAG, "Failed to recognize device")
throw it
}
val name = DeviceUtil.getName(deviceInfo, pid?.type) val name = DeviceUtil.getName(deviceInfo, pid?.type)
deviceInfo.model(name, device is NfcYubiKeyDevice, pid?.value) return deviceInfo.model(name, device is NfcYubiKeyDevice, pid?.value)
} }
} catch (exception: Exception) {
Log.e(OathManager.TAG, "No connection available for getting device info")
throw exception
}
}
}

View File

@ -0,0 +1,106 @@
package com.yubico.authenticator.yubikit
import com.yubico.authenticator.device.Info
import com.yubico.authenticator.management.model
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.Transport
import com.yubico.yubikit.core.UsbPid
import com.yubico.yubikit.core.Version
import com.yubico.yubikit.core.YubiKeyDevice
import com.yubico.yubikit.management.DeviceConfig
import com.yubico.yubikit.management.DeviceInfo
import com.yubico.yubikit.management.FormFactor
import java.util.regex.Pattern
class SkyHelper {
companion object {
private val VERSION_0 = Version(0, 0, 0)
private val VERSION_3 = Version(3, 0, 0)
private val VERSION_4 = Version(4, 0, 0)
private val USB_VERSION_STRING_PATTERN: Pattern =
Pattern.compile("\\b(\\d{1,3})\\.(\\d)(\\d+)\\b")
/**
* Retrieves a [DeviceInfo] from USB Security YubiKey (SKY).
*
* Should be only used as last resort when all other DeviceInfo queries failed because
* the returned information might not be accurate.
*
* @param device YubiKeyDevice to get DeviceInfo for. Should be USB and SKY device
* @return [DeviceInfo] instance initialized with information from USB descriptors.
* @throws IllegalArgumentException if [device] is not instance of [UsbYubiKeyDevice] or
* if the USB device has wrong PID
*/
fun getDeviceInfo(device: YubiKeyDevice): Info {
if (device !is UsbYubiKeyDevice) {
throw IllegalArgumentException()
}
val pid = device.pid
if (pid !in listOf(UsbPid.YK4_FIDO, UsbPid.SKY_FIDO, UsbPid.NEO_FIDO)) {
throw IllegalArgumentException()
}
val usbVersion = validateVersionForPid(getVersionFromUsbDescriptor(device), pid)
// build DeviceInfo containing only USB product name and USB version
// we assume this is a Security Key based on the USB PID
return DeviceInfo(
DeviceConfig.Builder().enabledCapabilities(Transport.USB, 0).build(),
null,
usbVersion,
FormFactor.UNKNOWN,
mapOf(Transport.USB to 0),
false,
false,
true
).model(device.usbDevice.productName ?: "YubiKey Security Key", false, pid.value)
}
// try to convert USB version to YubiKey version
private fun getVersionFromUsbDescriptor(device: UsbYubiKeyDevice): Version {
val version = device.usbDevice.version
val match = USB_VERSION_STRING_PATTERN.matcher(version)
if (match.find()) {
val major = match.group(1)?.toByte() ?: 0
val minor = match.group(2)?.toByte() ?: 0
val patch = match.group(3)?.toByte() ?: 0
return Version(major, minor, patch)
}
return VERSION_0
}
/**
* Check whether usbVersion is in expected range defined by UsbPid
*
* @return original version or [Version(0,0,0)] indicating invalid/unknown version
*/
private fun validateVersionForPid(usbVersion: Version, pid: UsbPid): Version {
if ((pid == UsbPid.NEO_FIDO && usbVersion.inRange(VERSION_3, VERSION_4)) ||
(pid == UsbPid.SKY_FIDO && usbVersion.isAtLeast(VERSION_3)) ||
(pid == UsbPid.YK4_FIDO && usbVersion.isAtLeast(VERSION_4))
) {
return usbVersion
}
return VERSION_0
}
/** Check if this version is at least v1 and less than v2
* @return true if this is in range [v1,v2)
*/
private fun Version.inRange(v1: Version, v2: Version): Boolean {
return this >= v1 && this < v2
}
/** Check if this version is at least v
* @return true if this >= v
*/
private fun Version.isAtLeast(v: Version): Boolean {
return this >= v
}
}
}

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
<item name="android:defaultFocusHighlightEnabled">false</item>
</style>
</resources>

View File

@ -1,4 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="app_label">Yubico Authenticator</string> <string name="app_label">Yubico Authenticator Preview</string>
<string name="otp_success_set_otp_to_clipboard">Successfully copied OTP code from YubiKey to clipboard.</string>
<string name="otp_success_set_password_to_clipboard">Successfully copied password from YubiKey to clipboard.</string>
<string name="otp_parse_failure">Failed to parse OTP code from YubiKey.</string>
<string name="otp_set_clip_failure">Failed to access clipboard when trying to copy OTP code from YubiKey.</string>
</resources> </resources>

View File

@ -15,4 +15,15 @@
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar"> <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item> <item name="android:windowBackground">?android:colorBackground</item>
</style> </style>
<style name="NdefActivityTheme" parent="NormalTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources> </resources>

View File

@ -1,26 +1,31 @@
package com.yubico.authenticator.oath package com.yubico.authenticator.oath
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.yubico.authenticator.device.Version import com.yubico.authenticator.device.Version
import com.yubico.authenticator.oath.OathTestHelper.code import com.yubico.authenticator.oath.OathTestHelper.code
import com.yubico.authenticator.oath.OathTestHelper.emptyCredentials import com.yubico.authenticator.oath.OathTestHelper.emptyCredentials
import com.yubico.authenticator.oath.OathTestHelper.hotp import com.yubico.authenticator.oath.OathTestHelper.hotp
import com.yubico.authenticator.oath.OathTestHelper.totp import com.yubico.authenticator.oath.OathTestHelper.totp
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test import org.junit.Test
class ModelTest { class ModelTest {
private val model = Model() @get:Rule
val rule = InstantTaskExecutorRule()
private val viewModel = OathViewModel()
private fun connectDevice(deviceId: String) { private fun connectDevice(deviceId: String) {
model.session = Model.Session( viewModel.setSessionState(Model.Session(
deviceId, deviceId,
Version(1, 2, 3), Version(1, 2, 3),
isAccessKeySet = false, isAccessKeySet = false,
isRemembered = false, isRemembered = false,
isLocked = false isLocked = false
) ))
} }
@Test @Test
@ -29,53 +34,40 @@ class ModelTest {
assertEquals(0x20.toByte(), Model.OathType.TOTP.value) assertEquals(0x20.toByte(), Model.OathType.TOTP.value)
} }
@Test
fun `hotp is interactive`() {
assertTrue(hotp().isInteractive())
}
@Test
fun `totp with touch is interactive`() {
assertTrue(totp(touchRequired = true).isInteractive())
}
@Test
fun `totp without touch is not interactive`() {
assertFalse(totp(touchRequired = false).isInteractive())
}
@Test @Test
fun `has no credentials after initialization`() { fun `has no credentials after initialization`() {
assertTrue(model.credentials.isEmpty()) assertNull(viewModel.credentials.value)
} }
@Test @Test
fun `updates empty model`() { fun `updates empty model`() {
val d = "device1" val d = "device1"
connectDevice(d)
val m = mapOf(totp(d) to code()) val m = mapOf(totp(d) to code())
model.update(d, m) viewModel.updateCredentials(m)
assertEquals(1, model.credentials.size) assertEquals(1, viewModel.credentials.value?.size)
} }
@Test @Test
fun `replaces credentials on device change`() { fun `replaces credentials on device change`() {
val d1 = "device1" val d1 = "device1"
connectDevice(d1)
val m1 = mapOf( val m1 = mapOf(
totp(d1) to code(), totp(d1) to code(),
totp(d1) to code() totp(d1) to code()
) )
model.update(d1, m1) viewModel.updateCredentials(m1)
val d2 = "device2" connectDevice("device2")
val m2 = emptyCredentials() val m2 = emptyCredentials()
model.update(d2, m2) viewModel.updateCredentials(m2)
assertTrue(model.credentials.isEmpty()) assertTrue(viewModel.credentials.value!!.isEmpty())
model.update(d1, m1) connectDevice("device1")
assertEquals(2, model.credentials.size) viewModel.updateCredentials(m1)
assertEquals(2, viewModel.credentials.value!!.size)
} }
@Test @Test
@ -92,7 +84,7 @@ class ModelTest {
cred2 to code() cred2 to code()
) )
connectDevice(d1) connectDevice(d1)
model.update(d1, m1) viewModel.updateCredentials(m1)
// one more credential was added // one more credential was added
val m2 = mapOf( val m2 = mapOf(
@ -101,13 +93,13 @@ class ModelTest {
cred1 to code() cred1 to code()
) )
model.update(d1, m2) viewModel.updateCredentials(m2)
assertEquals("device1", model.session?.deviceId) assertEquals("device1", viewModel.sessionState.value?.deviceId)
assertEquals(3, model.credentials.size) assertEquals(3, viewModel.credentials.value!!.size)
assertTrue(model.credentials.find { it.credential == cred1 } != null) assertTrue(viewModel.credentials.value!!.find { it.credential == cred1 } != null)
assertTrue(model.credentials.find { it.credential == cred2 } != null) assertTrue(viewModel.credentials.value!!.find { it.credential == cred2 } != null)
assertTrue(model.credentials.find { it.credential == cred3 } != null) assertTrue(viewModel.credentials.value!!.find { it.credential == cred3 } != null)
} }
@Test @Test
@ -115,21 +107,24 @@ class ModelTest {
val cred = totp(name = "cred1") val cred = totp(name = "cred1")
val code = code(value = "123456") val code = code(value = "123456")
val m1 = mapOf(cred to code) val m1 = mapOf(cred to code)
model.update(cred.deviceId, m1)
assertTrue(model.credentials.find { it.code == code } != null) connectDevice(cred.deviceId)
viewModel.updateCredentials(m1)
assertTrue(viewModel.credentials.value?.find { it.code == code } != null)
val updatedCode = code(value = "121212") val updatedCode = code(value = "121212")
val m2 = mapOf(cred to updatedCode) val m2 = mapOf(cred to updatedCode)
model.update(cred.deviceId, m2) viewModel.updateCredentials(m2)
assertTrue(model.credentials.find { it.code == updatedCode } != null) assertTrue(viewModel.credentials.value?.find { it.code == updatedCode } != null)
} }
@Test @Test
fun `update uses all credentials from its input `() { fun `update uses all credentials from its input `() {
val d = "device" val d = "device"
model.update(d, emptyCredentials()) connectDevice(d)
viewModel.updateCredentials(emptyCredentials())
// in next update the device has credentials // in next update the device has credentials
val totp1 = totp(deviceId = d, name = "totp1", touchRequired = false) val totp1 = totp(deviceId = d, name = "totp1", touchRequired = false)
@ -142,49 +137,51 @@ class ModelTest {
val code4 = code(value = "4444") val code4 = code(value = "4444")
val m1 = mapOf(totp1 to code1, totp2 to code2, hotp1 to code3, hotp2 to code4) val m1 = mapOf(totp1 to code1, totp2 to code2, hotp1 to code3, hotp2 to code4)
model.update(d, m1) viewModel.updateCredentials(m1)
// all four are present // all four are present
val foundTotp1 = model.credentials.find { it.credential == totp1 } val foundTotp1 = viewModel.credentials.value?.find { it.credential == totp1 }
assertTrue(foundTotp1 != null) assertTrue(foundTotp1 != null)
assertEquals("111111", foundTotp1?.code?.value) assertEquals("111111", foundTotp1?.code?.value)
val foundTotp2 = model.credentials.find { it.credential == totp2 } val foundTotp2 = viewModel.credentials.value?.find { it.credential == totp2 }
assertTrue(foundTotp2 != null) assertTrue(foundTotp2 != null)
assertEquals("222222", foundTotp2?.code?.value) assertEquals("222222", foundTotp2?.code?.value)
val foundHotp1 = model.credentials.find { it.credential == hotp1 } val foundHotp1 = viewModel.credentials.value?.find { it.credential == hotp1 }
assertTrue(foundHotp1 != null) assertTrue(foundHotp1 != null)
assertEquals("33333", foundHotp1?.code?.value) assertEquals("33333", foundHotp1?.code?.value)
val foundHotp2 = model.credentials.find { it.credential == hotp2 } val foundHotp2 = viewModel.credentials.value?.find { it.credential == hotp2 }
assertTrue(foundHotp2 != null) assertTrue(foundHotp2 != null)
assertEquals("4444", foundHotp2?.code?.value) assertEquals("4444", foundHotp2?.code?.value)
} }
@Test @Test
fun `update preserves non-interactive codes`() { fun `update without code preserves existing value`() {
val d = "device" val d = "device"
val totp = totp(d, name = "totpCred") val totp = totp(d, name = "totpCred")
val totpCode: Model.Code? = null val totpCode: Model.Code? = null
val hotp = hotp(d, name = "hotpCred") val hotp = hotp(d, name = "hotpCred")
val hotpCode: Model.Code? = null val hotpCode: Model.Code? = code(value = "098765")
val m1 = mapOf(hotp to hotpCode, totp to totpCode) val m1 = mapOf(hotp to hotpCode, totp to totpCode)
model.update(d, m1)
assertTrue(model.credentials.find { it.code == hotpCode } != null) connectDevice(d)
viewModel.updateCredentials(m1)
assertTrue(viewModel.credentials.value?.find { it.code == hotpCode } != null)
val updatedTotpCode = code(value = "121212") val updatedTotpCode = code(value = "121212")
val updatedHotpCode = code(value = "098765") val updatedHotpCode = null
val m2 = mapOf(hotp to updatedHotpCode, totp to updatedTotpCode) val m2 = mapOf(hotp to updatedHotpCode, totp to updatedTotpCode)
model.update(d, m2) viewModel.updateCredentials(m2)
assertTrue(model.credentials.find { it.code == updatedTotpCode } != null) assertTrue(viewModel.credentials.value?.find { it.code == updatedTotpCode } != null)
assertTrue(model.credentials.find { it.code == hotpCode } != null) assertTrue(viewModel.credentials.value?.find { it.code == hotpCode } != null)
assertFalse(model.credentials.find { it.code == updatedHotpCode } != null) assertFalse(viewModel.credentials.value?.find { it.code == updatedHotpCode } != null)
} }
@Test @Test
@ -194,17 +191,18 @@ class ModelTest {
val totpCode: Model.Code? = null val totpCode: Model.Code? = null
connectDevice(d) connectDevice(d)
model.update(d, mapOf(totp to totpCode)) viewModel.updateCredentials(mapOf(totp to totpCode))
// simulate touch // simulate touch
val newCode = model.updateCode(d, totp, code(value = "00000")) viewModel.updateCode(totp, code(value = "00000"))
val newCode = viewModel.credentials.value?.find { it.credential == totp }?.code
assertNotNull(newCode) assertNotNull(newCode)
// update with same values // update with same values
model.update(d, mapOf(totp to newCode)) viewModel.updateCredentials(mapOf(totp to newCode))
assertEquals(1, model.credentials.size) assertEquals(1, viewModel.credentials.value?.size)
assertEquals("00000", model.credentials.find { it.credential == totp }?.code?.value) assertEquals("00000", viewModel.credentials.value?.find { it.credential == totp }?.code?.value)
} }
@Test @Test
@ -212,16 +210,17 @@ class ModelTest {
val d = "Device" val d = "Device"
val t1 = totp() val t1 = totp()
val c1 = code() val c1 = code()
model.update(d, mapOf(t1 to c1)) connectDevice(d)
viewModel.updateCredentials(mapOf(t1 to c1))
val t2 = totp() val t2 = totp()
val c2 = code() val c2 = code()
val t3 = totp() val t3 = totp()
val c3 = code() val c3 = code()
model.update(d, mapOf(t3 to c3, t2 to c2, t1 to c1)) viewModel.updateCredentials(mapOf(t3 to c3, t2 to c2, t1 to c1))
// t3 and t2 are added to credentials // t3 and t2 are added to credentials
assertEquals(3, model.credentials.size) assertEquals(3, viewModel.credentials.value?.size)
} }
@Test @Test
@ -234,30 +233,35 @@ class ModelTest {
val t3 = totp() val t3 = totp()
val c3 = code() val c3 = code()
model.update(d, mapOf(t3 to c3, t1 to c1, t2 to c2)) connectDevice(d)
assertEquals(3, model.credentials.size) viewModel.updateCredentials(mapOf(t3 to c3, t1 to c1, t2 to c2))
assertEquals(3, viewModel.credentials.value?.size)
model.update(d, mapOf(t1 to c1)) viewModel.updateCredentials(mapOf(t1 to c1))
// only t1 is part of credentials // only t1 is part of credentials
assertEquals(1, model.credentials.size) assertEquals(1, viewModel.credentials.value?.size)
assertTrue(model.credentials.find { it.credential == t1 } != null) assertTrue(viewModel.credentials.value?.find { it.credential == t1 } != null)
} }
@Test @Test
fun `adds one credential with code to empty`() { fun `adds one credential with code to empty`() {
val d = "device" val d = "device"
model.update(d, mapOf(totp() to code())) connectDevice(d)
viewModel.updateCredentials(mapOf(totp() to code()))
assertEquals(1, model.credentials.size) assertEquals(1, viewModel.credentials.value?.size)
} }
@Test @Test
fun `does not add one credential with code to not initialized model`() { fun `does not add one credential with code to not initialized model`() {
val d = "device" val d = "device"
model.add(d, totp(), code()) connectDevice(d)
assertThrows(IllegalArgumentException::class.java) {
viewModel.addCredential(totp(), code())
}
assertEquals(0, model.credentials.size) assertEquals(0, viewModel.credentials.value?.size ?: 0)
} }
@Test @Test
@ -265,15 +269,17 @@ class ModelTest {
val d1 = "device1" val d1 = "device1"
val d2 = "device2" val d2 = "device2"
connectDevice(d1) connectDevice(d1)
model.update(d1, mapOf(totp() to code())) viewModel.updateCredentials(mapOf(totp(d1) to code()))
// cannot add to this model // cannot add to this model
assertNull(model.add(d2, totp(), code())) assertThrows(IllegalArgumentException::class.java) {
viewModel.addCredential(totp(), code())
}
// can add to this model // can add to this model
assertNotNull(model.add(d1, totp(), code())) assertNotNull(viewModel.addCredential(totp(d1), code()))
assertEquals(2, model.credentials.size) assertEquals(2, viewModel.credentials.value?.size)
} }
@Test @Test
@ -284,18 +290,23 @@ class ModelTest {
val code1 = code() val code1 = code()
connectDevice(d1) connectDevice(d1)
model.update(d1, mapOf(toRename to code1)) viewModel.updateCredentials(mapOf(toRename to code1))
val renamedForD2 = totp(d2, name = "newName", issuer = "newIssuer") val renamedForD2 = totp(d2, name = "newName", issuer = "newIssuer")
assertNull(model.rename(d1, toRename, renamedForD2)) assertThrows(IllegalArgumentException::class.java) {
viewModel.renameCredential(toRename, renamedForD2)
}
val renamedForD1 = totp(d1, name = "newName", issuer = "newIssuer") val renamedForD1 = totp(d1, name = "newName", issuer = "newIssuer")
// trying to rename on wrong device // trying to rename on wrong device
assertNull(model.rename(d2, toRename, renamedForD2)) assertThrows(IllegalArgumentException::class.java) {
viewModel.renameCredential(toRename, renamedForD2)
}
// rename success // rename success
val renamed = model.rename(d1, toRename, renamedForD1) viewModel.renameCredential(toRename, renamedForD1)
val renamed = viewModel.credentials.value?.find { it.credential == renamedForD1 }?.credential
assertNotNull(renamed) assertNotNull(renamed)
// the name and issuer are correct // the name and issuer are correct
@ -310,15 +321,17 @@ class ModelTest {
val code1 = code() val code1 = code()
connectDevice(d) connectDevice(d)
model.update(d, mapOf(toRename to code1)) viewModel.updateCredentials(mapOf(toRename to code1))
val nullIssuer = totp(d, name = "newName", issuer = null) val nullIssuer = totp(d, name = "newName", issuer = null)
val renamed = model.rename(d, toRename, nullIssuer) viewModel.renameCredential(toRename, nullIssuer)
val renamed = viewModel.credentials.value?.find { it.credential == nullIssuer }?.credential
assertNull(renamed!!.issuer) assertNull(renamed!!.issuer)
val nonNullIssuer = totp(d, name = "newName", issuer = "valueHere") val nonNullIssuer = totp(d, name = "newName", issuer = "valueHere")
val renamed2 = model.rename(d, renamed, nonNullIssuer) viewModel.renameCredential(nullIssuer, nonNullIssuer)
val renamed2 = viewModel.credentials.value?.find { it.credential == nonNullIssuer }?.credential
assertNotNull(renamed2!!.issuer) assertNotNull(renamed2!!.issuer)
} }
@ -333,16 +346,17 @@ class ModelTest {
val code2 = code(value = "00000") val code2 = code(value = "00000")
connectDevice(d1) connectDevice(d1)
model.update(d1, mapOf(totpD1 to code1)) viewModel.updateCredentials(mapOf(totpD1 to code1))
// cant update on different device
assertNull(model.updateCode(d2, totpD1, code()))
// cant update for credential from different device // cant update for credential from different device
assertNull(model.updateCode(d1, totpD2, code())) // TODO: This should fail
assertThrows(NullPointerException::class.java) {
viewModel.updateCode(totpD2, code())
}
// updates correctly to new code // updates correctly to new code
val newCode = model.updateCode(d1, totpD1, code2) viewModel.updateCode(totpD1, code2)
val newCode = viewModel.credentials.value?.find { it.credential == totpD1 }?.code
assertNotNull(newCode) assertNotNull(newCode)
assertEquals("00000", newCode!!.value!!) assertEquals("00000", newCode!!.value!!)
} }
@ -351,10 +365,10 @@ class ModelTest {
fun `removes data on reset`() { fun `removes data on reset`() {
val deviceId = "device" val deviceId = "device"
connectDevice(deviceId) connectDevice(deviceId)
model.update(deviceId, mapOf(totp() to code())) viewModel.updateCredentials(mapOf(totp() to code()))
model.reset() viewModel.setSessionState(null)
assertNull(model.session) assertNull(viewModel.sessionState.value)
assertTrue(model.credentials.isEmpty()) assertNull(viewModel.credentials.value)
} }
} }

View File

@ -1,6 +1,7 @@
package com.yubico.authenticator.oath package com.yubico.authenticator.oath
import com.yubico.authenticator.device.Version import com.yubico.authenticator.device.Version
import com.yubico.authenticator.jsonSerializer
import com.yubico.authenticator.oath.OathTestHelper.code import com.yubico.authenticator.oath.OathTestHelper.code
import com.yubico.authenticator.oath.OathTestHelper.hotp import com.yubico.authenticator.oath.OathTestHelper.hotp
import com.yubico.authenticator.oath.OathTestHelper.totp import com.yubico.authenticator.oath.OathTestHelper.totp

View File

@ -0,0 +1,194 @@
package com.yubico.authenticator.yubikit
import android.hardware.usb.UsbDevice
import com.yubico.authenticator.device.Version
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.UsbPid
import org.junit.Assert.*
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
class SkyHelperTest {
@Test
fun `passing NfcYubiKeyDevice will throw`() {
assertThrows(IllegalArgumentException::class.java) {
SkyHelper.getDeviceInfo(mock(NfcYubiKeyDevice::class.java))
}
}
@Test
fun `supports three specific UsbPids`() {
for (pid in UsbPid.values()) {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(pid)
}
if (pid in listOf(UsbPid.YK4_FIDO, UsbPid.SKY_FIDO, UsbPid.NEO_FIDO)) {
// these will not throw
assertNotNull(SkyHelper.getDeviceInfo(ykDevice))
} else {
// all other will throw
assertThrows(IllegalArgumentException::class.java) {
SkyHelper.getDeviceInfo(ykDevice)
}
}
}
}
@Test
fun `handles NEO_FIDO versions`() {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.NEO_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(3, 0, 0))
}
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(3, 4, 7))
}
// lower than 3 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("2.10")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
// greater or equal 4.0.0 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
}
@Test
fun `handles SKY_FIDO versions`() {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.SKY_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(3, 0, 0))
}
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(3, 4, 7))
}
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(4, 0, 0))
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(4, 3, 7))
}
// lower than 3 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("2.10")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
}
@Test
fun `handles YK4_FIDO versions`() {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.YK4_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(4, 0, 0))
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, Version(4, 3, 7))
}
// lower than 4 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
}
@Test
fun `returns Version 0 for invalid input`() {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.SKY_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("yubico")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("4")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.0")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.0.0")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.version, VERSION_0)
}
}
@Test
fun `returns default product name`() {
val ykDevice = getUsbYubiKeyDeviceMock()
`when`(ykDevice.pid).thenReturn(UsbPid.SKY_FIDO)
`when`(ykDevice.usbDevice.version).thenReturn("5.50")
`when`(ykDevice.usbDevice.productName).thenReturn(null)
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.name, "YubiKey Security Key")
}
}
companion object {
fun getUsbYubiKeyDeviceMock(): UsbYubiKeyDevice = mock(UsbYubiKeyDevice::class.java).also {
`when`(it.pid).thenReturn(UsbPid.YKS_OTP)
`when`(it.usbDevice).thenReturn(mock(UsbDevice::class.java))
`when`(it.usbDevice.productName).thenReturn("")
`when`(it.usbDevice.version).thenReturn("")
}
private val VERSION_0 = Version(0, 0, 0)
}
}

View File

@ -1,14 +1,15 @@
buildscript { buildscript {
ext.kotlin_version = '1.6.21' ext.kotlin_version = '1.7.10'
repositories { repositories {
google() google()
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:7.1.3' classpath 'com.android.tools.build:gradle:7.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.5'
} }
} }
@ -16,6 +17,7 @@ allprojects {
repositories { repositories {
google() google()
mavenCentral() mavenCentral()
mavenLocal() // TODO: Remove this before release
} }
project.ext { project.ext {
@ -24,7 +26,7 @@ allprojects {
compileSdkVersion = 32 compileSdkVersion = 32
buildToolsVersion = "30.0.3" buildToolsVersion = "30.0.3"
yubiKitVersion = "2.1.0-alpha.1" yubiKitVersion = "2.1.0"
junitVersion = "4.13.2" junitVersion = "4.13.2"
mockitoVersion = "3.9.0" mockitoVersion = "3.9.0"
} }

View File

@ -1,8 +1,8 @@
group 'com.yubico.authenticator.flutter_plugins.qrscanner_zxing' group 'com.yubico.authenticator.flutter_plugins.qrscanner_zxing'
version '1.0-SNAPSHOT' version '1.0'
buildscript { buildscript {
ext.kotlin_version = '1.6.21' ext.kotlin_version = '1.7.10'
repositories { repositories {
google() google()
mavenCentral() mavenCentral()
@ -46,7 +46,7 @@ android {
} }
dependencies { dependencies {
def camerax_version = "1.1.0-beta03" def camerax_version = "1.1.0"
implementation "androidx.camera:camera-lifecycle:${camerax_version}" implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation "androidx.camera:camera-view:${camerax_version}" implementation "androidx.camera:camera-view:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}" implementation "androidx.camera:camera-camera2:${camerax_version}"

View File

@ -3,18 +3,22 @@ package com.yubico.authenticator.flutter_plugins.qrscanner_zxing
import android.Manifest import android.Manifest
import android.app.Activity import android.app.Activity
import android.content.Context import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.provider.Settings
import android.util.Log import android.util.Log
import android.view.View import android.view.View
import android.widget.TextView
import androidx.camera.core.* import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.google.zxing.* import com.google.zxing.*
import com.google.zxing.common.HybridBinarizer import com.google.zxing.common.HybridBinarizer
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
@ -52,12 +56,13 @@ typealias BarcodeAnalyzerListener = (Result<String>) -> Unit
internal class QRScannerView( internal class QRScannerView(
context: Context, context: Context,
id: Int, @Suppress("UNUSED_PARAMETER") id : Int,
binaryMessenger: BinaryMessenger, binaryMessenger: BinaryMessenger,
private val permissionsResultRegistrar: PermissionsResultRegistrar, private val permissionsResultRegistrar: PermissionsResultRegistrar,
creationParams: Map<String?, Any?>? creationParams: Map<String?, Any?>?
) : PlatformView { ) : PlatformView {
private val stateChangeObserver = StateChangeObserver(context)
private val uiThreadHandler = Handler(Looper.getMainLooper()) private val uiThreadHandler = Handler(Looper.getMainLooper())
private var marginPct: Double? = null private var marginPct: Double? = null
@ -97,8 +102,8 @@ internal class QRScannerView(
private val qrScannerView = View.inflate(context, R.layout.qr_scanner_view, null) private val qrScannerView = View.inflate(context, R.layout.qr_scanner_view, null)
private val previewView = qrScannerView.findViewById<PreviewView>(R.id.preview_view).also { private val previewView = qrScannerView.findViewById<PreviewView>(R.id.preview_view).also {
it.scaleType = PreviewView.ScaleType.FILL_CENTER it.scaleType = PreviewView.ScaleType.FILL_CENTER
it.implementationMode = PreviewView.ImplementationMode.PERFORMANCE
} }
private val infoText = qrScannerView.findViewById<TextView>(R.id.info_text)
private val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor() private val cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val cameraProviderFuture = ProcessCameraProvider.getInstance(context) private val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
@ -117,6 +122,7 @@ internal class QRScannerView(
preview = null preview = null
imageAnalyzer = null imageAnalyzer = null
cameraExecutor.shutdown() cameraExecutor.shutdown()
methodChannel.setMethodCallHandler(null)
Log.d(TAG, "View disposed") Log.d(TAG, "View disposed")
} }
@ -142,6 +148,20 @@ internal class QRScannerView(
} else { } else {
bindUseCases(context) bindUseCases(context)
} }
methodChannel.setMethodCallHandler { call, _ ->
if (call.method =="requestCameraPermissions") {
requestPermissionsFromUser(context)
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + context.getPackageName())
)
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(context, intent, null)
}
}
} }
} }
@ -159,17 +179,14 @@ internal class QRScannerView(
grantResults.first() == PackageManager.PERMISSION_GRANTED grantResults.first() == PackageManager.PERMISSION_GRANTED
) { ) {
previewView.visibility = View.VISIBLE previewView.visibility = View.VISIBLE
infoText.visibility = View.GONE
bindUseCases(activity) bindUseCases(activity)
} else { } else {
previewView.visibility = View.GONE previewView.visibility = View.GONE
infoText.visibility = View.VISIBLE reportViewInitialized(false)
infoText.setText(R.string.please_grant_permissions)
} }
} else { } else {
previewView.visibility = View.GONE previewView.visibility = View.GONE
infoText.visibility = View.VISIBLE reportViewInitialized(false)
infoText.setText(R.string.please_grant_permissions)
} }
return true return true
} }
@ -181,8 +198,28 @@ internal class QRScannerView(
requestPermissions(activity) requestPermissions(activity)
} }
private fun reportViewInitialized(permissionsGranted: Boolean) {
uiThreadHandler.post {
methodChannel.invokeMethod(
"viewInitialized",
JSONObject(mapOf("permissionsGranted" to permissionsGranted)).toString()
)
}
}
private fun reportCodeFound(code: String) {
uiThreadHandler.post {
methodChannel.invokeMethod(
"codeFound", JSONObject(
mapOf("value" to code)
).toString()
)
}
}
private fun bindUseCases(context: Context) { private fun bindUseCases(context: Context) {
cameraProviderFuture.addListener({ cameraProviderFuture.addListener({
previewView.visibility = View.VISIBLE previewView.visibility = View.VISIBLE
cameraProvider = cameraProviderFuture.get() cameraProvider = cameraProviderFuture.get()
@ -196,13 +233,7 @@ internal class QRScannerView(
it.setAnalyzer(cameraExecutor, BarcodeAnalyzer(marginPct) { analyzeResult -> it.setAnalyzer(cameraExecutor, BarcodeAnalyzer(marginPct) { analyzeResult ->
if (analyzeResult.isSuccess) { if (analyzeResult.isSuccess) {
analyzeResult.getOrNull()?.let { result -> analyzeResult.getOrNull()?.let { result ->
uiThreadHandler.post { reportCodeFound(result)
methodChannel.invokeMethod(
"codeFound", JSONObject(
mapOf("value" to result)
).toString()
)
}
} }
} }
}) })
@ -215,11 +246,18 @@ internal class QRScannerView(
it.setSurfaceProvider(previewView.surfaceProvider) it.setSurfaceProvider(previewView.surfaceProvider)
} }
cameraProvider?.bindToLifecycle( val camera = cameraProvider?.bindToLifecycle(
context as LifecycleOwner, context as LifecycleOwner,
cameraSelector, cameraSelector,
preview, imageAnalyzer preview, imageAnalyzer
) )
camera?.cameraInfo?.cameraState?.let {
it.removeObservers(context as LifecycleOwner)
it.observe(context as LifecycleOwner, stateChangeObserver)
}
reportViewInitialized(true)
}, ContextCompat.getMainExecutor(context)) }, ContextCompat.getMainExecutor(context))
} }
@ -275,4 +313,24 @@ internal class QRScannerView(
} }
} }
private class StateChangeObserver(val context: Context) : Observer<CameraState> {
private var cameraOpened: Boolean = false
override fun onChanged(t: CameraState) {
Log.d(TAG, "Camera state changed to ${t.type}")
if (t.type == CameraState.Type.OPEN) {
cameraOpened = true
}
if (cameraOpened && t.type == CameraState.Type.CLOSED) {
Log.d(TAG, "Camera closed")
val stateChangedIntent =
Intent("com.yubico.authenticator.QRScannerView.CameraClosed")
context.sendBroadcast(stateChangedIntent)
cameraOpened = false
}
}
}
} }

View File

@ -1,6 +1,5 @@
package com.yubico.authenticator.flutter_plugins.qrscanner_zxing package com.yubico.authenticator.flutter_plugins.qrscanner_zxing
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
@ -38,7 +37,7 @@ class QRScannerZxingPlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
private val registrar = PermissionsResultRegistrar() private val registrar = PermissionsResultRegistrar()
private lateinit var channel: MethodChannel private lateinit var channel: MethodChannel
override fun onAttachedToEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "qrscanner_zxing") channel = MethodChannel(binding.binaryMessenger, "qrscanner_zxing")
channel.setMethodCallHandler(this) channel.setMethodCallHandler(this)
@ -49,7 +48,7 @@ class QRScannerZxingPlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
) )
} }
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getPlatformVersion") { if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}") result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else { } else {
@ -57,7 +56,7 @@ class QRScannerZxingPlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
} }
} }
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null) channel.setMethodCallHandler(null)
} }

View File

@ -2,28 +2,12 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@android:color/background_dark"> android:background="@android:color/black">
<TextView
android:id="@+id/info_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="@android:color/black"
android:background="@android:color/background_light"
android:gravity="left"
android:textSize="12sp"
android:lineSpacingMultiplier="1.2"
android:layout_margin="32dp"
android:padding="16dp"
android:drawableStart="@android:drawable/ic_dialog_alert"
android:drawablePadding="16dp"
android:text="@string/please_grant_permissions" />
<androidx.camera.view.PreviewView <androidx.camera.view.PreviewView
android:visibility="gone"
android:id="@+id/preview_view" android:id="@+id/preview_view"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" /> android:layout_height="match_parent"
android:visibility="gone" />
</FrameLayout> </FrameLayout>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="please_grant_permissions">The QR scanner cannot work properly because grant of Camera permissions is missing.\n\nPlease, fix this by changing the Camera permissions setting in the phone Settings.</string>
<string name="initializing">Please wait…</string>
</resources>

View File

@ -79,6 +79,9 @@ class QRScannerPageState extends State<QRScannerPage> {
right: 0, right: 0,
child: QRScannerZxingView( child: QRScannerZxingView(
marginPct: 10, marginPct: 10,
onViewInitialized: (permissionsGranted) {
// this example does not handle Camera permissions
},
onDetect: (result) { onDetect: (result) {
if (currentCode == null) { if (currentCode == null) {
setState(() { setState(() {

View File

@ -9,9 +9,13 @@ import 'package:flutter/services.dart';
class QRScannerZxingView extends StatefulWidget { class QRScannerZxingView extends StatefulWidget {
final int marginPct; final int marginPct;
final Function(String rawData) onDetect; final Function(String rawData) onDetect;
final Function(bool permissionsGranted) onViewInitialized;
const QRScannerZxingView( const QRScannerZxingView(
{Key? key, required this.marginPct, required this.onDetect}) {Key? key,
required this.marginPct,
required this.onDetect,
required this.onViewInitialized})
: super(key: key); : super(key: key);
@override @override
@ -31,6 +35,11 @@ class QRScannerZxingViewState extends State<QRScannerZxingView> {
var rawValue = arguments["value"]; var rawValue = arguments["value"];
widget.onDetect(rawValue); widget.onDetect(rawValue);
return; return;
case "viewInitialized":
var arguments = jsonDecode(call.arguments);
var permissionsGranted = arguments["permissionsGranted"];
widget.onViewInitialized(permissionsGranted);
return;
} }
} catch (e) { } catch (e) {
if (kDebugMode) { if (kDebugMode) {
@ -40,6 +49,11 @@ class QRScannerZxingViewState extends State<QRScannerZxingView> {
}); });
} }
void requestPermissions() {
debugPrint("Permissions requested");
channel.invokeMethod("requestCameraPermissions", null);
}
@override @override
void dispose() { void dispose() {
super.dispose(); super.dispose();

BIN
android/gradle/wrapper/gradle-wrapper.jar vendored Executable file

Binary file not shown.

6
android/gradle/wrapper/gradle-wrapper.properties vendored Normal file → Executable file
View File

@ -1,6 +1,6 @@
#Fri Jun 23 08:50:38 CEST 2017 #Mon Aug 15 14:34:17 CEST 2022
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip zipStoreBase=GRADLE_USER_HOME

160
android/gradlew vendored Executable file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
android/gradlew.bat vendored Executable file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,203 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,131 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

View File

@ -0,0 +1,685 @@
Classpath is distributed under the terms of the GNU General Public License with the following clarification and special exception.
Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination.
As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.
As such, it can be used to run, create and distribute a large class of applications and applets. When GNU Classpath is used unmodified as the core class library for a virtual machine, compiler for the java languge, or for a program written in the java programming language it does not affect the licensing for distributing those programs directly.
----
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,210 @@
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial code and documentation
distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from and are
distributed by that particular Contributor. A Contribution 'originates' from
a Contributor if it was added to the Program by such Contributor itself or
anyone acting on such Contributor's behalf. Contributions do not include additions
to the Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii) are
not derivative works of the Program.
"Contributor" means any person or entity that distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which are
necessarily infringed by the use or sale of its Contribution alone or when
combined with the Program.
"Program" means the Contributions distributed in accordance with this Agreement.
"Recipient" means anyone who receives the Program under this Agreement, including
all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce,
prepare derivative works of, publicly display, publicly perform, distribute
and sublicense the Contribution of such Contributor, if any, and such derivative
works, in source code and object code form.
b) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed
Patents to make, use, sell, offer to sell, import and otherwise transfer the
Contribution of such Contributor, if any, in source code and object code form.
This patent license shall apply to the combination of the Contribution and
the Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered by
the Licensed Patents. The patent license shall not apply to any other combinations
which include the Contribution. No hardware per se is licensed hereunder.
c) Recipient understands that although each Contributor grants the licenses
to its Contributions set forth herein, no assurances are provided by any Contributor
that the Program does not infringe the patent or other intellectual property
rights of any other entity. Each Contributor disclaims any liability to Recipient
for claims brought by any other entity based on infringement of intellectual
property rights or otherwise. As a condition to exercising the rights and
licenses granted hereunder, each Recipient hereby assumes sole responsibility
to secure any other intellectual property rights needed, if any. For example,
if a third party patent license is required to allow Recipient to distribute
the Program, it is Recipient's responsibility to acquire that license before
distributing the Program.
d) Each Contributor represents that to its knowledge it has sufficient copyright
rights in its Contribution, if any, to grant the copyright license set forth
in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code form under
its own license agreement, provided that:
a) it complies with the terms and conditions of this Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors all warranties and
conditions, express and implied, including warranties or conditions of title
and non-infringement, and implied warranties or conditions of merchantability
and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors all liability for damages,
including direct, indirect, special, incidental and consequential damages,
such as lost profits;
iii) states that any provisions which differ from this Agreement are offered
by that Contributor alone and not by any other party; and
iv) states that source code for the Program is available from such Contributor,
and informs licensees how to obtain it in a reasonable manner on or through
a medium customarily used for software exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each copy of the Program.
Contributors may not remove or alter any copyright notices contained within
the Program.
Each Contributor must identify itself as the originator of its Contribution,
if any, in a manner that reasonably allows subsequent Recipients to identify
the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities with
respect to end users, business partners and the like. While this license is
intended to facilitate the commercial use of the Program, the Contributor
who includes the Program in a commercial product offering should do so in
a manner which does not create potential liability for other Contributors.
Therefore, if a Contributor includes the Program in a commercial product offering,
such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify
every other Contributor ("Indemnified Contributor") against any losses, damages
and costs (collectively "Losses") arising from claims, lawsuits and other
legal actions brought by a third party against the Indemnified Contributor
to the extent caused by the acts or omissions of such Commercial Contributor
in connection with its distribution of the Program in a commercial product
offering. The obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In order
to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
Contributor in writing of such claim, and b) allow the Commercial Contributor
to control, and cooperate with the Commercial Contributor in, the defense
and any related settlement negotiations. The Indemnified Contributor may participate
in any such claim at its own expense.
For example, a Contributor might include the Program in a commercial product
offering, Product X. That Contributor is then a Commercial Contributor. If
that Commercial Contributor then makes performance claims, or offers warranties
related to Product X, those performance claims and warranties are such Commercial
Contributor's responsibility alone. Under this section, the Commercial Contributor
would have to defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other Contributor
to pay any damages as a result, the Commercial Contributor must pay those
damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON
AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
Each Recipient is solely responsible for determining the appropriateness of
using and distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to the
risks and costs of program errors, compliance with applicable laws, damage
to or loss of data, programs or equipment, and unavailability or interruption
of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS
GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under applicable
law, it shall not affect the validity or enforceability of the remainder of
the terms of this Agreement, and without further action by the parties hereto,
such provision shall be reformed to the minimum extent necessary to make such
provision valid and enforceable.
If Recipient institutes patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Program itself
(excluding combinations of the Program with other software or hardware) infringes
such Recipient's patent(s), then such Recipient's rights granted under Section
2(b) shall terminate as of the date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it fails to
comply with any of the material terms or conditions of this Agreement and
does not cure such failure in a reasonable period of time after becoming aware
of such noncompliance. If all Recipient's rights under this Agreement terminate,
Recipient agrees to cease use and distribution of the Program as soon as reasonably
practicable. However, Recipient's obligations under this Agreement and any
licenses granted by Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement, but
in order to avoid inconsistency the Agreement is copyrighted and may only
be modified in the following manner. The Agreement Steward reserves the right
to publish new versions (including revisions) of this Agreement from time
to time. No one other than the Agreement Steward has the right to modify this
Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse
Foundation may assign the responsibility to serve as the Agreement Steward
to a suitable separate entity. Each new version of the Agreement will be given
a distinguishing version number. The Program (including Contributions) may
always be distributed subject to the version of the Agreement under which
it was received. In addition, after a new version of the Agreement is published,
Contributor may elect to distribute the Program (including its Contributions)
under the new version. Except as expressly stated in Sections 2(a) and 2(b)
above, Recipient receives no rights or licenses to the intellectual property
of any Contributor under this Agreement, whether expressly, by implication,
estoppel or otherwise. All rights in the Program not expressly granted under
this Agreement are reserved.
This Agreement is governed by the laws of the State of New York and the intellectual
property laws of the United States of America. No party to this Agreement
will bring a legal action under this Agreement more than one year after the
cause of action arose. Each party waives its rights to a jury trial in any
resulting litigation.

View File

@ -0,0 +1,8 @@
{
"http://www.apache.org/licenses/LICENSE-2.0.txt": "apache-2.0.txt",
"https://www.apache.org/licenses/LICENSE-2.0.txt": "apache-2.0.txt",
"http://www.eclipse.org/legal/epl-v10.html": "eclipse-1.0.txt",
"http://www.gnu.org/software/classpath/license.html": "classpath.txt",
"http://opensource.org/licenses/MIT": "mit.txt",
"http://creativecommons.org/licenses/publicdomain": "cc0-1.0.txt"
}

9
android/licenses/mit.txt Normal file
View File

@ -0,0 +1,9 @@
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
assets/graphics/yubico-green.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
assets/graphics/yubico-white.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

View File

@ -1 +1,2 @@
helper.json helper.json
android/**

0
assets/licenses/android/.gitignore vendored Normal file
View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 27 KiB

112
helper/poetry.lock generated
View File

@ -8,7 +8,7 @@ python-versions = "*"
[[package]] [[package]]
name = "atomicwrites" name = "atomicwrites"
version = "1.4.0" version = "1.4.1"
description = "Atomic file writes." description = "Atomic file writes."
category = "dev" category = "dev"
optional = false optional = false
@ -16,17 +16,17 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
[[package]] [[package]]
name = "attrs" name = "attrs"
version = "21.4.0" version = "22.1.0"
description = "Classes Without Boilerplate" description = "Classes Without Boilerplate"
category = "dev" category = "dev"
optional = false optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" python-versions = ">=3.5"
[package.extras] [package.extras]
dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "zope.interface", "furo", "sphinx", "sphinx-notfound-page", "pre-commit", "cloudpickle"] dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope.interface", "furo", "sphinx", "sphinx-notfound-page", "pre-commit", "cloudpickle"]
docs = ["furo", "sphinx", "zope.interface", "sphinx-notfound-page"] docs = ["furo", "sphinx", "zope.interface", "sphinx-notfound-page"]
tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "zope.interface", "cloudpickle"] tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope.interface", "cloudpickle"]
tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "cloudpickle"] tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "cloudpickle"]
[[package]] [[package]]
name = "cffi" name = "cffi"
@ -137,7 +137,7 @@ trio = ["trio", "async-generator"]
[[package]] [[package]]
name = "keyring" name = "keyring"
version = "23.6.0" version = "23.8.2"
description = "Store and access your passwords safely." description = "Store and access your passwords safely."
category = "main" category = "main"
optional = false optional = false
@ -151,7 +151,7 @@ SecretStorage = {version = ">=3.2", markers = "sys_platform == \"linux\""}
[package.extras] [package.extras]
docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)", "jaraco.tidelift (>=1.4)"] docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)", "jaraco.tidelift (>=1.4)"]
testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"] testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "flake8 (<5)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"]
[[package]] [[package]]
name = "macholib" name = "macholib"
@ -174,7 +174,7 @@ python-versions = ">=3.5"
[[package]] [[package]]
name = "numpy" name = "numpy"
version = "1.23.0" version = "1.23.1"
description = "NumPy is the fundamental package for array computing with Python." description = "NumPy is the fundamental package for array computing with Python."
category = "main" category = "main"
optional = false optional = false
@ -244,7 +244,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
[[package]] [[package]]
name = "pyinstaller" name = "pyinstaller"
version = "5.1" version = "5.3"
description = "PyInstaller bundles a Python application and all its dependencies into a single package." description = "PyInstaller bundles a Python application and all its dependencies into a single package."
category = "dev" category = "dev"
optional = false optional = false
@ -253,7 +253,7 @@ python-versions = "<3.11,>=3.7"
[package.dependencies] [package.dependencies]
altgraph = "*" altgraph = "*"
macholib = {version = ">=1.8", markers = "sys_platform == \"darwin\""} macholib = {version = ">=1.8", markers = "sys_platform == \"darwin\""}
pefile = {version = ">=2017.8.1", markers = "sys_platform == \"win32\""} pefile = {version = ">=2022.5.30", markers = "sys_platform == \"win32\""}
pyinstaller-hooks-contrib = ">=2021.4" pyinstaller-hooks-contrib = ">=2021.4"
pywin32-ctypes = {version = ">=0.2.0", markers = "sys_platform == \"win32\""} pywin32-ctypes = {version = ">=0.2.0", markers = "sys_platform == \"win32\""}
@ -263,7 +263,7 @@ hook_testing = ["pytest (>=2.7.3)", "execnet (>=1.5.0)", "psutil"]
[[package]] [[package]]
name = "pyinstaller-hooks-contrib" name = "pyinstaller-hooks-contrib"
version = "2022.7" version = "2022.8"
description = "Community maintained hooks for PyInstaller" description = "Community maintained hooks for PyInstaller"
category = "dev" category = "dev"
optional = false optional = false
@ -374,15 +374,15 @@ resolved_reference = "32612d177db0d8dd768679ce26c4e509d10f2a97"
[[package]] [[package]]
name = "zipp" name = "zipp"
version = "3.8.0" version = "3.8.1"
description = "Backport of pathlib-compatible object wrapper for zip files" description = "Backport of pathlib-compatible object wrapper for zip files"
category = "main" category = "main"
optional = false optional = false
python-versions = ">=3.7" python-versions = ">=3.7"
[package.extras] [package.extras]
docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)"] docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)", "jaraco.tidelift (>=1.4)"]
testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"] testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.3)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"]
[[package]] [[package]]
name = "zxing-cpp" name = "zxing-cpp"
@ -405,14 +405,8 @@ altgraph = [
{file = "altgraph-0.17.2-py2.py3-none-any.whl", hash = "sha256:743628f2ac6a7c26f5d9223c91ed8ecbba535f506f4b6f558885a8a56a105857"}, {file = "altgraph-0.17.2-py2.py3-none-any.whl", hash = "sha256:743628f2ac6a7c26f5d9223c91ed8ecbba535f506f4b6f558885a8a56a105857"},
{file = "altgraph-0.17.2.tar.gz", hash = "sha256:ebf2269361b47d97b3b88e696439f6e4cbc607c17c51feb1754f90fb79839158"}, {file = "altgraph-0.17.2.tar.gz", hash = "sha256:ebf2269361b47d97b3b88e696439f6e4cbc607c17c51feb1754f90fb79839158"},
] ]
atomicwrites = [ atomicwrites = []
{file = "atomicwrites-1.4.0-py2.py3-none-any.whl", hash = "sha256:6d1784dea7c0c8d4a5172b6c620f40b6e4cbfdf96d783691f2e1302a7b88e197"}, attrs = []
{file = "atomicwrites-1.4.0.tar.gz", hash = "sha256:ae70396ad1a434f9c7046fd2dd196fc04b12f9e91ffb859164193be8b6168a7a"},
]
attrs = [
{file = "attrs-21.4.0-py2.py3-none-any.whl", hash = "sha256:2d27e3784d7a565d36ab851fe94887c5eccd6a463168875832a1be79c82828b4"},
{file = "attrs-21.4.0.tar.gz", hash = "sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd"},
]
cffi = [ cffi = [
{file = "cffi-1.15.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2"}, {file = "cffi-1.15.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2"},
{file = "cffi-1.15.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2"}, {file = "cffi-1.15.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2"},
@ -530,10 +524,7 @@ jeepney = [
{file = "jeepney-0.8.0-py3-none-any.whl", hash = "sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755"}, {file = "jeepney-0.8.0-py3-none-any.whl", hash = "sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755"},
{file = "jeepney-0.8.0.tar.gz", hash = "sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806"}, {file = "jeepney-0.8.0.tar.gz", hash = "sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806"},
] ]
keyring = [ keyring = []
{file = "keyring-23.6.0-py3-none-any.whl", hash = "sha256:372ff2fc43ab779e3f87911c26e6c7acc8bb440cbd82683e383ca37594cb0617"},
{file = "keyring-23.6.0.tar.gz", hash = "sha256:3ac00c26e4c93739e19103091a9986a9f79665a78cf15a4df1dba7ea9ac8da2f"},
]
macholib = [ macholib = [
{file = "macholib-1.16-py2.py3-none-any.whl", hash = "sha256:5a0742b587e6e57bfade1ab90651d4877185bf66fd4a176a488116de36878229"}, {file = "macholib-1.16-py2.py3-none-any.whl", hash = "sha256:5a0742b587e6e57bfade1ab90651d4877185bf66fd4a176a488116de36878229"},
{file = "macholib-1.16.tar.gz", hash = "sha256:001bf281279b986a66d7821790d734e61150d52f40c080899df8fefae056e9f7"}, {file = "macholib-1.16.tar.gz", hash = "sha256:001bf281279b986a66d7821790d734e61150d52f40c080899df8fefae056e9f7"},
@ -542,30 +533,7 @@ mss = [
{file = "mss-6.1.0-py3-none-any.whl", hash = "sha256:2722c5c9211ce29b4f1497fc2c70faecf9cdcb7653fa7f0f88e2231a31949b93"}, {file = "mss-6.1.0-py3-none-any.whl", hash = "sha256:2722c5c9211ce29b4f1497fc2c70faecf9cdcb7653fa7f0f88e2231a31949b93"},
{file = "mss-6.1.0.tar.gz", hash = "sha256:aebd069f3e05667fe9c7b9fa4b1771fe42a4710ce1058ce0236936ce06fa5394"}, {file = "mss-6.1.0.tar.gz", hash = "sha256:aebd069f3e05667fe9c7b9fa4b1771fe42a4710ce1058ce0236936ce06fa5394"},
] ]
numpy = [ numpy = []
{file = "numpy-1.23.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:58bfd40eb478f54ff7a5710dd61c8097e169bc36cc68333d00a9bcd8def53b38"},
{file = "numpy-1.23.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:196cd074c3f97c4121601790955f915187736f9cf458d3ee1f1b46aff2b1ade0"},
{file = "numpy-1.23.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f1d88ef79e0a7fa631bb2c3dda1ea46b32b1fe614e10fedd611d3d5398447f2f"},
{file = "numpy-1.23.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d54b3b828d618a19779a84c3ad952e96e2c2311b16384e973e671aa5be1f6187"},
{file = "numpy-1.23.0-cp310-cp310-win32.whl", hash = "sha256:2b2da66582f3a69c8ce25ed7921dcd8010d05e59ac8d89d126a299be60421171"},
{file = "numpy-1.23.0-cp310-cp310-win_amd64.whl", hash = "sha256:97a76604d9b0e79f59baeca16593c711fddb44936e40310f78bfef79ee9a835f"},
{file = "numpy-1.23.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d8cc87bed09de55477dba9da370c1679bd534df9baa171dd01accbb09687dac3"},
{file = "numpy-1.23.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:f0f18804df7370571fb65db9b98bf1378172bd4e962482b857e612d1fec0f53e"},
{file = "numpy-1.23.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ac86f407873b952679f5f9e6c0612687e51547af0e14ddea1eedfcb22466babd"},
{file = "numpy-1.23.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae8adff4172692ce56233db04b7ce5792186f179c415c37d539c25de7298d25d"},
{file = "numpy-1.23.0-cp38-cp38-win32.whl", hash = "sha256:fe8b9683eb26d2c4d5db32cd29b38fdcf8381324ab48313b5b69088e0e355379"},
{file = "numpy-1.23.0-cp38-cp38-win_amd64.whl", hash = "sha256:5043bcd71fcc458dfb8a0fc5509bbc979da0131b9d08e3d5f50fb0bbb36f169a"},
{file = "numpy-1.23.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1c29b44905af288b3919803aceb6ec7fec77406d8b08aaa2e8b9e63d0fe2f160"},
{file = "numpy-1.23.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:98e8e0d8d69ff4d3fa63e6c61e8cfe2d03c29b16b58dbef1f9baa175bbed7860"},
{file = "numpy-1.23.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79a506cacf2be3a74ead5467aee97b81fca00c9c4c8b3ba16dbab488cd99ba10"},
{file = "numpy-1.23.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:092f5e6025813e64ad6d1b52b519165d08c730d099c114a9247c9bb635a2a450"},
{file = "numpy-1.23.0-cp39-cp39-win32.whl", hash = "sha256:d6ca8dabe696c2785d0c8c9b0d8a9b6e5fdbe4f922bde70d57fa1a2848134f95"},
{file = "numpy-1.23.0-cp39-cp39-win_amd64.whl", hash = "sha256:fc431493df245f3c627c0c05c2bd134535e7929dbe2e602b80e42bf52ff760bc"},
{file = "numpy-1.23.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:f9c3fc2adf67762c9fe1849c859942d23f8d3e0bee7b5ed3d4a9c3eeb50a2f07"},
{file = "numpy-1.23.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0d2094e8f4d760500394d77b383a1b06d3663e8892cdf5df3c592f55f3bff66"},
{file = "numpy-1.23.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:94b170b4fa0168cd6be4becf37cb5b127bd12a795123984385b8cd4aca9857e5"},
{file = "numpy-1.23.0.tar.gz", hash = "sha256:bd3fa4fe2e38533d5336e1272fc4e765cabbbde144309ccee8675509d5cd7b05"},
]
packaging = [ packaging = [
{file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"},
{file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"},
@ -645,23 +613,8 @@ pycparser = [
{file = "pycparser-2.21-py2.py3-none-any.whl", hash = "sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9"}, {file = "pycparser-2.21-py2.py3-none-any.whl", hash = "sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9"},
{file = "pycparser-2.21.tar.gz", hash = "sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"}, {file = "pycparser-2.21.tar.gz", hash = "sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"},
] ]
pyinstaller = [ pyinstaller = []
{file = "pyinstaller-5.1-py3-none-macosx_10_13_universal2.whl", hash = "sha256:3c9bc373b4a4bf6d81b306b9918e290a3de582d7b50a0f6f4e837970a4db0c54"}, pyinstaller-hooks-contrib = []
{file = "pyinstaller-5.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:ac003d49bbd62f6712b5631487049cee4f0a07445dd31c6d05e5724e33689fca"},
{file = "pyinstaller-5.1-py3-none-manylinux2014_i686.whl", hash = "sha256:f786cb013ebfd3fb23ddb46285902663e31256220b12b368f8c36e859a77ebc9"},
{file = "pyinstaller-5.1-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:d8bfe5c32b4b5aaa91a5c1c7912fe3e5d13e7671f3468ee7742ec71ca192a975"},
{file = "pyinstaller-5.1-py3-none-manylinux2014_s390x.whl", hash = "sha256:c421b46ebf81ad4498de480640ce1a47ac15dfd3938dfc2e1c0846cb5cdb0c59"},
{file = "pyinstaller-5.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:588f2840c27a8a7e1b1fa361f107a1060c5096b36d3c94c243b23687ee41609d"},
{file = "pyinstaller-5.1-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:d3852c1f8fe6ca2f5c7942c845dc6d1f6140aa7860fe3500eac3ac88875d1dd4"},
{file = "pyinstaller-5.1-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:29b3f17d75ff58b12db7b0116df1b3382c8345aefd500a177987eaf0599dec03"},
{file = "pyinstaller-5.1-py3-none-win32.whl", hash = "sha256:a90ee3181c88aed0893bf537a50ad547655f5d555a5b731215a5fe1946d2f3db"},
{file = "pyinstaller-5.1-py3-none-win_amd64.whl", hash = "sha256:996e296d1dfe27c3e89efc26dbcc247f49c0801a9b5e22e2b39f5b983cf5c2f5"},
{file = "pyinstaller-5.1.tar.gz", hash = "sha256:9596c70c860cbce19537354db95b180351959b4cd14a70db6ab1d1432668c313"},
]
pyinstaller-hooks-contrib = [
{file = "pyinstaller-hooks-contrib-2022.7.tar.gz", hash = "sha256:6675634279cfe9e475580fb310c3d557037baefb065e6cb5a69a124361b926fd"},
{file = "pyinstaller_hooks_contrib-2022.7-py2.py3-none-any.whl", hash = "sha256:5fdb97dcae177955db7ab27840cba97b89dc0c7f4fd9142bba0f9b8d8df85c48"},
]
pyparsing = [ pyparsing = [
{file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"},
{file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"},
@ -706,24 +659,5 @@ tomli = [
{file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
] ]
yubikey-manager = [] yubikey-manager = []
zipp = [ zipp = []
{file = "zipp-3.8.0-py3-none-any.whl", hash = "sha256:c4f6e5bbf48e74f7a38e7cc5b0480ff42b0ae5178957d564d18932525d5cf099"}, zxing-cpp = []
{file = "zipp-3.8.0.tar.gz", hash = "sha256:56bf8aadb83c24db6c4b577e13de374ccfb67da2078beba1d037c17980bf43ad"},
]
zxing-cpp = [
{file = "zxing-cpp-1.4.0.tar.gz", hash = "sha256:3d3ec36954ecbf9b0f633dab4b8cebcf0059d8a27f7a5969c4e41a308111af38"},
{file = "zxing_cpp-1.4.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:25b11d77cf6b9f7405af3ed6bacf4a6e0756ea74dfda7040ff53e7c58f352b05"},
{file = "zxing_cpp-1.4.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c1f849205237d4bda462d0a4b745e72494f825e5b6b06581e05b58d34d9869aa"},
{file = "zxing_cpp-1.4.0-cp310-cp310-win32.whl", hash = "sha256:76e9777d943af3c51b6406b323b3f28cbf9e40cc65b53cf847fda08295f18e48"},
{file = "zxing_cpp-1.4.0-cp310-cp310-win_amd64.whl", hash = "sha256:234d672e34e607ffc8e06639e79c8e1bf2ddb7c249134a6836569e92a2f2dd64"},
{file = "zxing_cpp-1.4.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2c1f66c61e43163740c59c58880c3a8c41ebd2109573c0494f255c9c96134e8c"},
{file = "zxing_cpp-1.4.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9418e1bd0775820a4933b60007b7f8a177e4ddd23692c1aaed2348fafc0a8e01"},
{file = "zxing_cpp-1.4.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8bc1e48ddfd6692d183782f091fbf54e5e1d36d0070822b1eab14cfb580b1625"},
{file = "zxing_cpp-1.4.0-cp38-cp38-win32.whl", hash = "sha256:4f340b6907780e8eb0e6473fec43ea145c4dd3275e3c21d6f887c0e28e114f29"},
{file = "zxing_cpp-1.4.0-cp38-cp38-win_amd64.whl", hash = "sha256:71772f81c4602133b2dba6a1107339ed965725001ce9a4caaf772598110351a1"},
{file = "zxing_cpp-1.4.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:331bec6b0ac8a9b339bc82956c52c022e7b2debfeb9102209483eb7538ed72d4"},
{file = "zxing_cpp-1.4.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3b0844c6ad3c944452c980a025238ba3fbd3a414fd2c36e2bec1bc5bed03b21e"},
{file = "zxing_cpp-1.4.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a770aff618cd00dda3922de2f7085c1f84bbe02f2b6df114d19054ad41c52fb0"},
{file = "zxing_cpp-1.4.0-cp39-cp39-win32.whl", hash = "sha256:ebe67de6a4d3c48a5ee52211ecf2003301ab39bd7d7b7dfa72ae80be429cfcf9"},
{file = "zxing_cpp-1.4.0-cp39-cp39-win_amd64.whl", hash = "sha256:d0e8b54b29497ed9238f31ce522ddb0189c0d6c4597787ef2eb823ca9fb42350"},
]

3
l10n.yaml Normal file
View File

@ -0,0 +1,3 @@
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

View File

@ -3,17 +3,20 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'app/state.dart';
import 'version.dart';
import 'app/logging.dart'; import 'app/logging.dart';
import 'app/message.dart'; import 'app/message.dart';
import 'app/state.dart';
import 'core/state.dart'; import 'core/state.dart';
import 'android/state.dart';
import 'desktop/state.dart'; import 'desktop/state.dart';
import 'version.dart';
import 'widgets/responsive_dialog.dart'; import 'widgets/responsive_dialog.dart';
import 'widgets/choice_filter_chip.dart';
final _log = Logger('about'); final _log = Logger('about');
@ -23,7 +26,9 @@ class AboutPage extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
return ResponsiveDialog( return ResponsiveDialog(
title: const Text('About'), title: Text(AppLocalizations.of(context)!.general_about),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 32),
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@ -44,9 +49,10 @@ class AboutPage extends ConsumerWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextButton( TextButton(
child: const Text( child: Text(
'Terms of use', AppLocalizations.of(context)!.general_terms_of_use,
style: TextStyle(decoration: TextDecoration.underline), style:
const TextStyle(decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
launchUrl( launchUrl(
@ -57,9 +63,10 @@ class AboutPage extends ConsumerWidget {
}, },
), ),
TextButton( TextButton(
child: const Text( child: Text(
'Privacy policy', AppLocalizations.of(context)!.general_privacy_policy,
style: TextStyle(decoration: TextDecoration.underline), style:
const TextStyle(decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
launchUrl( launchUrl(
@ -72,9 +79,9 @@ class AboutPage extends ConsumerWidget {
], ],
), ),
TextButton( TextButton(
child: const Text( child: Text(
'Open source licenses', AppLocalizations.of(context)!.general_open_src_licenses,
style: TextStyle(decoration: TextDecoration.underline), style: const TextStyle(decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
Navigator.of(context).push(MaterialPageRoute<void>( Navigator.of(context).push(MaterialPageRoute<void>(
@ -92,7 +99,7 @@ class AboutPage extends ConsumerWidget {
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0), padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text( child: Text(
'Help and feedback', AppLocalizations.of(context)!.general_help_and_feedback,
style: Theme.of(context).textTheme.titleMedium, style: Theme.of(context).textTheme.titleMedium,
), ),
), ),
@ -100,21 +107,27 @@ class AboutPage extends ConsumerWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextButton( TextButton(
child: const Text( child: Text(
'Send us feedback', AppLocalizations.of(context)!.general_send_feedback,
style: TextStyle(decoration: TextDecoration.underline), style:
const TextStyle(decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
launchUrl( launchUrl(
Uri.parse('https://forms.gle/nYPVWcFnqoprZX1S9'), Platform.isAndroid
// Android Beta feedback form
? Uri.parse('https://forms.gle/2J81Kh8rnzBrtNc69')
// Desktop Beta feedback form
: Uri.parse('https://forms.gle/nYPVWcFnqoprZX1S9'),
mode: LaunchMode.externalApplication, mode: LaunchMode.externalApplication,
); );
}, },
), ),
TextButton( TextButton(
child: const Text( child: Text(
'I need help', AppLocalizations.of(context)!.general_i_need_help,
style: TextStyle(decoration: TextDecoration.underline), style:
const TextStyle(decoration: TextDecoration.underline),
), ),
onPressed: () { onPressed: () {
launchUrl( launchUrl(
@ -132,16 +145,19 @@ class AboutPage extends ConsumerWidget {
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0), padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text( child: Text(
'Troubleshooting', AppLocalizations.of(context)!.general_troubleshooting,
style: Theme.of(context).textTheme.titleMedium, style: Theme.of(context).textTheme.titleMedium,
), ),
), ),
const LoggingPanel(), const LoggingPanel(),
// Diagnostics (desktop only)
if (isDesktop) ...[ if (isDesktop) ...[
const SizedBox(height: 12.0), const SizedBox(height: 12.0),
OutlinedButton.icon( ActionChip(
icon: const Icon(Icons.bug_report_outlined), avatar: const Icon(Icons.bug_report_outlined),
label: const Text('Run diagnostics'), label:
Text(AppLocalizations.of(context)!.general_run_diagnostics),
onPressed: () async { onPressed: () async {
_log.info('Running diagnostics...'); _log.info('Running diagnostics...');
final response = final response =
@ -155,13 +171,32 @@ class AboutPage extends ConsumerWidget {
await Clipboard.setData(ClipboardData(text: text)); await Clipboard.setData(ClipboardData(text: text));
await ref.read(withContextProvider)( await ref.read(withContextProvider)(
(context) async { (context) async {
showMessage(context, 'Diagnostic data copied to clipboard'); showMessage(
context,
AppLocalizations.of(context)!
.general_diagnostics_copied);
}, },
); );
}, },
), ),
]
], ],
// Enable screenshots (Android only)
if (isAndroid) ...[
const SizedBox(height: 12.0),
FilterChip(
label: Text(
AppLocalizations.of(context)!.general_allow_screenshots),
selected: ref.watch(androidAllowScreenshotsProvider),
onSelected: (value) async {
ref
.read(androidAllowScreenshotsProvider.notifier)
.setAllowScreenshots(value);
},
),
],
],
),
), ),
); );
} }
@ -172,38 +207,40 @@ class LoggingPanel extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
return Column( final logLevel = ref.watch(logLevelProvider);
return Wrap(
alignment: WrapAlignment.center,
spacing: 4.0,
runSpacing: 8.0,
children: [ children: [
const SizedBox(height: 12.0), ChoiceFilterChip<Level>(
DropdownButtonFormField<Level>( avatar: Icon(
decoration: const InputDecoration( Icons.insights,
labelText: 'Log level', color: Theme.of(context).colorScheme.primary,
border: OutlineInputBorder(),
), ),
value: ref.watch(logLevelProvider), value: logLevel,
items: Levels.LEVELS items: Levels.LEVELS,
.map((e) => DropdownMenuItem( selected: logLevel != Level.INFO,
value: e, labelBuilder: (value) => Text(
child: Text(e.name.toUpperCase()), '${AppLocalizations.of(context)!.general_log_level}: ${value.name[0]}${value.name.substring(1).toLowerCase()}'),
)) itemBuilder: (value) =>
.toList(), Text('${value.name[0]}${value.name.substring(1).toLowerCase()}'),
onChanged: (level) { onChanged: (level) {
ref.read(logLevelProvider.notifier).setLogLevel(level!); ref.read(logLevelProvider.notifier).setLogLevel(level);
_log.debug('Log level set to $level'); _log.debug('Log level set to $level');
showMessage(context, 'Log level set to $level');
}, },
), ),
const SizedBox(height: 12.0), ActionChip(
OutlinedButton.icon( avatar: const Icon(Icons.copy),
icon: const Icon(Icons.copy), label: Text(AppLocalizations.of(context)!.general_copy_log),
label: const Text('Copy log to clipboard'),
onPressed: () async { onPressed: () async {
_log.info('Copying log to clipboard ($version)...'); _log.info('Copying log to clipboard ($version)...');
final logs = await ref.read(logLevelProvider.notifier).getLogs(); final logs = await ref.read(logLevelProvider.notifier).getLogs();
await Clipboard.setData(ClipboardData(text: logs.join('\n'))); await Clipboard.setData(ClipboardData(text: logs.join('\n')));
await ref.read(withContextProvider)( await ref.read(withContextProvider)(
(context) async { (context) async {
showMessage(context, 'Log copied to clipboard'); showMessage(
context, AppLocalizations.of(context)!.general_log_copied);
}, },
); );
}, },

View File

@ -1,15 +0,0 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../command_providers.dart';
import 'impl.dart';
class FManagementApiImpl extends FManagementApi {
final StateNotifierProviderRef _ref;
FManagementApiImpl(this._ref) : super();
@override
Future<void> updateDeviceInfo(String deviceInfoJson) async {
_ref.read(androidYubikeyProvider.notifier).setFromString(deviceInfoJson);
}
}

View File

@ -1,22 +0,0 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../oath/command_providers.dart';
import 'impl.dart';
class FOathApiImpl extends FOathApi {
final StateNotifierProviderRef _ref;
FOathApiImpl(this._ref) : super();
@override
Future<void> updateOathCredentials(String credentialListJson) async {
_ref
.read(androidCredentialsProvider.notifier)
.setFromString(credentialListJson);
}
@override
Future<void> updateSession(String sessionJson) async {
_ref.read(androidStateProvider.notifier).setFromString(sessionJson);
}
}

View File

@ -1,501 +0,0 @@
// Autogenerated from Pigeon (v3.1.6), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name
// @dart = 2.12
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
class UnlockResponse {
UnlockResponse({
this.isUnlocked,
this.isRemembered,
});
bool? isUnlocked;
bool? isRemembered;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['isUnlocked'] = isUnlocked;
pigeonMap['isRemembered'] = isRemembered;
return pigeonMap;
}
static UnlockResponse decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return UnlockResponse(
isUnlocked: pigeonMap['isUnlocked'] as bool?,
isRemembered: pigeonMap['isRemembered'] as bool?,
);
}
}
class _OathApiCodec extends StandardMessageCodec {
const _OathApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is UnlockResponse) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else
{
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return UnlockResponse.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class OathApi {
/// Constructor for [OathApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
OathApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _OathApiCodec();
Future<void> reset() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.reset', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<UnlockResponse> unlock(String arg_password, bool arg_remember) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.unlock', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_password, arg_remember]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as UnlockResponse?)!;
}
}
Future<void> setPassword(String? arg_currentPassword, String arg_newPassword) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.setPassword', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_currentPassword, arg_newPassword]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> unsetPassword(String arg_currentPassword) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.unsetPassword', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_currentPassword]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<void> forgetPassword() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.forgetPassword', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<String> addAccount(String arg_uri, bool arg_requireTouch) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.addAccount', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_uri, arg_requireTouch]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as String?)!;
}
}
Future<String> renameAccount(String arg_uri, String arg_name, String? arg_issuer) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.renameAccount', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_uri, arg_name, arg_issuer]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as String?)!;
}
}
Future<void> deleteAccount(String arg_uri) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.deleteAccount', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_uri]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
Future<String> refreshCodes() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.refreshCodes', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as String?)!;
}
}
Future<String> calculate(String arg_uri) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.OathApi.calculate', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_uri]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as String?)!;
}
}
}
class _AppApiCodec extends StandardMessageCodec {
const _AppApiCodec();
}
class AppApi {
/// Constructor for [AppApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
AppApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _AppApiCodec();
Future<void> setContext(int arg_subPageIndex) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AppApi.setContext', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_subPageIndex]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
}
class _FOathApiCodec extends StandardMessageCodec {
const _FOathApiCodec();
}
abstract class FOathApi {
static const MessageCodec<Object?> codec = _FOathApiCodec();
Future<void> updateSession(String sessionJson);
Future<void> updateOathCredentials(String credentialListJson);
static void setup(FOathApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FOathApi.updateSession', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.FOathApi.updateSession was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_sessionJson = (args[0] as String?);
assert(arg_sessionJson != null, 'Argument for dev.flutter.pigeon.FOathApi.updateSession was null, expected non-null String.');
await api.updateSession(arg_sessionJson!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FOathApi.updateOathCredentials', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.FOathApi.updateOathCredentials was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_credentialListJson = (args[0] as String?);
assert(arg_credentialListJson != null, 'Argument for dev.flutter.pigeon.FOathApi.updateOathCredentials was null, expected non-null String.');
await api.updateOathCredentials(arg_credentialListJson!);
return;
});
}
}
}
}
class _FManagementApiCodec extends StandardMessageCodec {
const _FManagementApiCodec();
}
abstract class FManagementApi {
static const MessageCodec<Object?> codec = _FManagementApiCodec();
Future<void> updateDeviceInfo(String deviceInfoJson);
static void setup(FManagementApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FManagementApi.updateDeviceInfo', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.FManagementApi.updateDeviceInfo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_deviceInfoJson = (args[0] as String?);
assert(arg_deviceInfoJson != null, 'Argument for dev.flutter.pigeon.FManagementApi.updateDeviceInfo was null, expected non-null String.');
await api.updateDeviceInfo(arg_deviceInfoJson!);
return;
});
}
}
}
}
class _FDialogApiCodec extends StandardMessageCodec {
const _FDialogApiCodec();
}
abstract class FDialogApi {
static const MessageCodec<Object?> codec = _FDialogApiCodec();
Future<void> showDialogApi(String dialogMessage);
Future<void> closeDialogApi();
static void setup(FDialogApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FDialogApi.showDialogApi', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null, 'Argument for dev.flutter.pigeon.FDialogApi.showDialogApi was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_dialogMessage = (args[0] as String?);
assert(arg_dialogMessage != null, 'Argument for dev.flutter.pigeon.FDialogApi.showDialogApi was null, expected non-null String.');
await api.showDialogApi(arg_dialogMessage!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FDialogApi.closeDialogApi', codec, binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
// ignore message
await api.closeDialogApi();
return;
});
}
}
}
}
class _HDialogApiCodec extends StandardMessageCodec {
const _HDialogApiCodec();
}
class HDialogApi {
/// Constructor for [HDialogApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
HDialogApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _HDialogApiCodec();
Future<void> dialogClosed() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.HDialogApi.dialogClosed', codec, binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error = (replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return;
}
}
}

View File

@ -1,65 +0,0 @@
import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:yubico_authenticator/android/oath/command_providers.dart';
import 'package:yubico_authenticator/app/logging.dart';
import '../app/models.dart';
import '../core/models.dart';
import '../management/models.dart';
final _log = Logger('yubikeyDataCommandProvider');
final androidYubikeyProvider =
StateNotifierProvider<_YubikeyProvider, AsyncValue<YubiKeyData>>((ref) {
return _YubikeyProvider(const AsyncValue.loading(), ref);
});
class _YubikeyProvider extends StateNotifier<AsyncValue<YubiKeyData>> {
final Ref _ref;
_YubikeyProvider(super.yubiKeyData, this._ref);
void setFromString(String input) {
try {
if (input.isEmpty) {
_log.debug('Yubikey was detached.');
state = const AsyncValue.loading();
// reset other providers when YubiKey is removed
_ref.refresh(androidStateProvider);
_ref.refresh(androidCredentialsProvider);
return;
}
var args = jsonDecode(input);
DeviceInfo deviceInfo = DeviceInfo.fromJson(args);
String name = args['name'];
bool isNfc = args['is_nfc'];
int? usbPid = args['usb_pid'];
DeviceNode deviceNode = isNfc
? DeviceNode.nfcReader(DevicePath([]), name)
: DeviceNode.usbYubiKey(
DevicePath([]),
name,
usbPid != null ? UsbPid.fromValue(usbPid) : UsbPid.yk4OtpFidoCcid,
deviceInfo);
// reset oath providers on key change
var yubiKeyData = YubiKeyData(deviceNode, name, deviceInfo);
state.whenData((data) {
if (data != yubiKeyData) {
_ref.refresh(androidStateProvider);
_ref.refresh(androidCredentialsProvider);
}
});
state = AsyncValue.data(yubiKeyData);
} on Exception catch (e) {
_log.debug('Invalid data for yubikey: $input. $e');
state = AsyncValue.error(e);
}
}
}

59
lib/android/devices.dart Normal file
View File

@ -0,0 +1,59 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import '../app/logging.dart';
import '../app/models.dart';
import '../core/models.dart';
import '../management/models.dart';
final _log = Logger('android.devices');
final androidYubikeyProvider =
StateNotifierProvider<_YubikeyProvider, AsyncValue<YubiKeyData>>((ref) {
return _YubikeyProvider();
});
class _YubikeyProvider extends StateNotifier<AsyncValue<YubiKeyData>> {
final _events = const EventChannel('android.devices.deviceInfo');
late StreamSubscription sub;
_YubikeyProvider() : super(const AsyncValue.loading()) {
sub = _events.receiveBroadcastStream().listen((event) {
_setDevice(jsonDecode(event));
});
}
@override
void dispose() {
sub.cancel();
super.dispose();
}
Future<void> _setDevice(Map<String, dynamic>? json) async {
if (json == null) {
_log.debug('Yubikey was detached.');
state = const AsyncValue.loading();
return;
}
state = await AsyncValue.guard(() async {
DeviceInfo deviceInfo = DeviceInfo.fromJson(json);
String name = json['name'];
bool isNfc = json['is_nfc'];
int? usbPid = json['usb_pid'];
DeviceNode deviceNode = isNfc
? DeviceNode.nfcReader(DevicePath([]), name)
: DeviceNode.usbYubiKey(
DevicePath([]),
name,
usbPid != null ? UsbPid.fromValue(usbPid) : UsbPid.yk4OtpFidoCcid,
deviceInfo);
return YubiKeyData(deviceNode, name, deviceInfo);
});
}
}

View File

@ -1,11 +1,14 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:yubico_authenticator/android/logger.dart'; import 'package:yubico_authenticator/android/logger.dart';
import 'package:yubico_authenticator/android/views/beta_dialog.dart';
import 'package:yubico_authenticator/android/window_state_provider.dart'; import 'package:yubico_authenticator/android/window_state_provider.dart';
import 'package:yubico_authenticator/app/logging.dart'; import 'package:yubico_authenticator/app/logging.dart';
@ -16,18 +19,19 @@ import '../app/views/main_page.dart';
import '../core/state.dart'; import '../core/state.dart';
import '../management/state.dart'; import '../management/state.dart';
import '../oath/state.dart'; import '../oath/state.dart';
import 'api/impl.dart';
import 'management/state.dart'; import 'management/state.dart';
import 'oath/state.dart'; import 'oath/state.dart';
import 'qr_scanner/qr_scanner_provider.dart'; import 'qr_scanner/qr_scanner_provider.dart';
import 'state.dart'; import 'state.dart';
import 'views/tap_request_dialog.dart'; import 'tap_request_dialog.dart';
Future<Widget> initialize() async { Future<Widget> initialize() async {
if (kDebugMode) { if (kDebugMode) {
Logger.root.level = Levels.DEBUG; Logger.root.level = Levels.DEBUG;
} }
_initLicenses();
return ProviderScope( return ProviderScope(
overrides: [ overrides: [
supportedAppsProvider.overrideWithValue([ supportedAppsProvider.overrideWithValue([
@ -47,6 +51,7 @@ Future<Widget> initialize() async {
qrScannerProvider.overrideWithProvider(androidQrScannerProvider), qrScannerProvider.overrideWithProvider(androidQrScannerProvider),
windowStateProvider.overrideWithProvider(androidWindowStateProvider) windowStateProvider.overrideWithProvider(androidWindowStateProvider)
], ],
child: DismissKeyboard(
child: YubicoAuthenticatorApp(page: Consumer( child: YubicoAuthenticatorApp(page: Consumer(
builder: (context, ref, child) { builder: (context, ref, child) {
// activates the sub page provider // activates the sub page provider
@ -56,9 +61,75 @@ Future<Widget> initialize() async {
ref.read(androidWindowStateProvider); ref.read(androidWindowStateProvider);
/// initializes global handler for dialogs /// initializes global handler for dialogs
FDialogApi.setup(FDialogApiImpl(ref.watch(withContextProvider))); ref.read(androidDialogProvider);
var betaDialog = BetaDialog(context, ref);
betaDialog.request();
return const MainPage(); return const MainPage();
}, },
)), )),
),
); );
} }
class DismissKeyboard extends StatelessWidget {
final Widget child;
const DismissKeyboard({super.key, required this.child});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// De-select any selected node when tapping outside.
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus?.unfocus();
}
},
child: child,
);
}
}
void _initLicenses() async {
const licenseDir = 'assets/licenses/android';
final androidProjectsToLicenseUrl = await rootBundle.loadStructuredData<List>(
'$licenseDir/android.json',
(value) async => jsonDecode(value),
);
// mapping from url to license text
final fileMap = await rootBundle.loadStructuredData<Map>(
'$licenseDir/map.json',
(value) async => jsonDecode(value),
);
final urlToLicense = <String, String>{};
fileMap.forEach((url, file) async {
String licenseText = url;
try {
licenseText = await rootBundle.loadString('$licenseDir/$file');
urlToLicense[url] = licenseText;
} catch (_) {
// failed to read license file, will use the url
}
});
if (androidProjectsToLicenseUrl.isNotEmpty) {
LicenseRegistry.addLicense(() async* {
for (final e in androidProjectsToLicenseUrl) {
var licenseUrl = e['PackageLicense'];
var content = licenseUrl;
if (urlToLicense.containsKey(licenseUrl)) {
content = '${urlToLicense[licenseUrl]}\n\n$licenseUrl\n\n';
}
yield LicenseEntryWithLineBreaks([e['PackageName']], content);
}
});
}
}

View File

@ -36,11 +36,18 @@ class AndroidLogger extends LogLevelNotifier {
} }
void log(LogRecord record) { void log(LogRecord record) {
final error = record.error == null
? null
: record.error is Exception
? record.error.toString()
: record.error is String
? record.error
: 'Invalid error type: ${record.error.runtimeType.toString()}';
_channel.invokeMethod('log', { _channel.invokeMethod('log', {
'loggerName': record.loggerName, 'loggerName': record.loggerName,
'level': record.level.name, 'level': record.level.name,
'message': record.message, 'message': record.message,
'error': record.error 'error': error
}); });
} }
} }

View File

@ -1,38 +0,0 @@
import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../oath/models.dart';
final androidStateProvider =
StateNotifierProvider<_StateProvider, OathState?>((ref) {
return _StateProvider(null);
});
class _StateProvider extends StateNotifier<OathState?> {
_StateProvider(super.oathState);
void setFromString(String input) {
var resultJson = jsonDecode(input);
state = OathState.fromJson(resultJson);
}
}
final androidCredentialsProvider =
StateNotifierProvider<_CredentialsProvider, List<OathPair>?>((ref) {
return _CredentialsProvider(null);
});
class _CredentialsProvider extends StateNotifier<List<OathPair>?> {
_CredentialsProvider(super.credentials);
void setFromString(String input) {
var result = jsonDecode(input);
if (result is List) {
state = result.map((e) => OathPair.fromJson(e)).toList();
} else {
state = [];
}
}
}

View File

@ -1,50 +1,57 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
import 'package:yubico_authenticator/android/api/impl.dart';
import 'package:yubico_authenticator/app/logging.dart';
import 'package:yubico_authenticator/app/models.dart';
import 'package:yubico_authenticator/app/state.dart';
import 'package:yubico_authenticator/core/models.dart';
import 'package:yubico_authenticator/oath/state.dart';
import '../../app/logging.dart';
import '../../app/models.dart';
import '../../app/state.dart';
import '../../app/views/user_interaction.dart';
import '../../cancellation_exception.dart';
import '../../core/models.dart';
import '../../oath/models.dart'; import '../../oath/models.dart';
import 'command_providers.dart'; import '../../oath/state.dart';
final _log = Logger('android.oath.state'); final _log = Logger('android.oath.state');
class CancelException implements Exception {} const _methods = MethodChannel('android.oath.methods');
final oathApiProvider = StateProvider((_) => OathApi());
final androidOathStateProvider = StateNotifierProvider.autoDispose final androidOathStateProvider = StateNotifierProvider.autoDispose
.family<OathStateNotifier, AsyncValue<OathState>, DevicePath>( .family<OathStateNotifier, AsyncValue<OathState>, DevicePath>(
(ref, devicePath) => _AndroidOathStateNotifier( (ref, devicePath) => _AndroidOathStateNotifier());
ref.watch(androidStateProvider), ref.watch(oathApiProvider), ref));
class _AndroidOathStateNotifier extends OathStateNotifier { class _AndroidOathStateNotifier extends OathStateNotifier {
final OathApi _api; final _events = const EventChannel('android.oath.sessionState');
final Ref _ref; late StreamSubscription _sub;
_AndroidOathStateNotifier() : super() {
_AndroidOathStateNotifier(OathState? newState, this._api, this._ref) _sub = _events.receiveBroadcastStream().listen((event) {
: super() { final json = jsonDecode(event);
if (newState != null) { if (mounted) {
setData(newState); if (json == null) {
state = const AsyncValue.loading();
} else {
final oathState = OathState.fromJson(json);
state = AsyncValue.data(oathState);
} }
} }
}, onError: (err, stackTrace) {
state = AsyncValue.error(err, stackTrace: stackTrace);
});
}
@override
void dispose() {
_sub.cancel();
super.dispose();
}
@override @override
Future<void> reset() async { Future<void> reset() async {
try { try {
await _api.reset(); await _methods.invokeMethod('reset');
setData(state.value!
.copyWith(locked: false, remembered: false, hasKey: false));
_ref.refresh(androidStateProvider);
} catch (e) { } catch (e) {
_log.debug('Calling reset failed with exception: $e'); _log.debug('Calling reset failed with exception: $e');
} }
@ -54,18 +61,13 @@ class _AndroidOathStateNotifier extends OathStateNotifier {
Future<Pair<bool, bool>> unlock(String password, Future<Pair<bool, bool>> unlock(String password,
{bool remember = false}) async { {bool remember = false}) async {
try { try {
final unlockResponse = await _api.unlock(password, remember); final unlockResponse = jsonDecode(await _methods.invokeMethod(
'unlock', {'password': password, 'remember': remember}));
final unlocked = unlockResponse.isUnlocked == true;
final remembered = unlockResponse.isRemembered == true;
if (unlocked) {
_log.debug('applet unlocked'); _log.debug('applet unlocked');
setData(state.value!.copyWith(
locked: false, final unlocked = unlockResponse['unlocked'] == true;
remembered: remembered, final remembered = unlockResponse['remembered'] == true;
));
}
return Pair(unlocked, remembered); return Pair(unlocked, remembered);
} on PlatformException catch (e) { } on PlatformException catch (e) {
_log.debug('Calling unlock failed with exception: $e'); _log.debug('Calling unlock failed with exception: $e');
@ -76,8 +78,8 @@ class _AndroidOathStateNotifier extends OathStateNotifier {
@override @override
Future<bool> setPassword(String? current, String password) async { Future<bool> setPassword(String? current, String password) async {
try { try {
await _api.setPassword(current, password); await _methods.invokeMethod(
setData(state.value!.copyWith(hasKey: true)); 'setPassword', {'current': current, 'password': password});
return true; return true;
} on PlatformException catch (e) { } on PlatformException catch (e) {
_log.debug('Calling set password failed with exception: $e'); _log.debug('Calling set password failed with exception: $e');
@ -88,8 +90,7 @@ class _AndroidOathStateNotifier extends OathStateNotifier {
@override @override
Future<bool> unsetPassword(String current) async { Future<bool> unsetPassword(String current) async {
try { try {
await _api.unsetPassword(current); await _methods.invokeMethod('unsetPassword', {'current': current});
setData(state.value!.copyWith(hasKey: false, locked: false));
return true; return true;
} on PlatformException catch (e) { } on PlatformException catch (e) {
_log.debug('Calling unset password failed with exception: $e'); _log.debug('Calling unset password failed with exception: $e');
@ -100,8 +101,7 @@ class _AndroidOathStateNotifier extends OathStateNotifier {
@override @override
Future<void> forgetPassword() async { Future<void> forgetPassword() async {
try { try {
await _api.forgetPassword(); await _methods.invokeMethod('forgetPassword');
setData(state.value!.copyWith(remembered: false));
} on PlatformException catch (e) { } on PlatformException catch (e) {
_log.debug('Calling forgetPassword failed with exception: $e'); _log.debug('Calling forgetPassword failed with exception: $e');
} }
@ -112,177 +112,127 @@ final androidCredentialListProvider = StateNotifierProvider.autoDispose
.family<OathCredentialListNotifier, List<OathPair>?, DevicePath>( .family<OathCredentialListNotifier, List<OathPair>?, DevicePath>(
(ref, devicePath) { (ref, devicePath) {
var notifier = _AndroidCredentialListNotifier( var notifier = _AndroidCredentialListNotifier(
ref.watch(currentDeviceProvider), ref.watch(withContextProvider),
ref.watch(oathApiProvider), ref.watch(currentDeviceProvider)?.transport == Transport.usb,
ref.watch(androidCredentialsProvider),
); );
ref.listen<WindowState>(windowStateProvider, (_, windowState) {
notifier._notifyWindowState(windowState);
}, fireImmediately: true);
return notifier; return notifier;
}, },
); );
class _AndroidCredentialListNotifier extends OathCredentialListNotifier { class _AndroidCredentialListNotifier extends OathCredentialListNotifier {
final DeviceNode? _currentDevice; final _events = const EventChannel('android.oath.credentials');
final OathApi _api; final WithContext _withContext;
Timer? _timer; final bool _isUsbAttached;
late StreamSubscription _sub;
_AndroidCredentialListNotifier( _AndroidCredentialListNotifier(this._withContext, this._isUsbAttached)
this._currentDevice, this._api, List<OathPair>? pairs)
: super() { : super() {
state = pairs; _sub = _events.receiveBroadcastStream().listen((event) {
_scheduleRefresh(); final json = jsonDecode(event);
} state = json != null
? List.unmodifiable(
void _notifyWindowState(WindowState windowState) { (json as List).map((e) => OathPair.fromJson(e)).toList())
if (_currentDevice == null) return; : null;
if (windowState.active) { });
_scheduleRefresh();
} else {
_timer?.cancel();
}
} }
@override @override
void dispose() { void dispose() {
_timer?.cancel(); _sub.cancel();
super.dispose(); super.dispose();
} }
@override @override
@protected Future<OathCode> calculate(OathCredential credential) async {
set state(List<OathPair>? value) { // Prompt for touch if needed
super.state = value != null ? List.unmodifiable(value) : null; UserInteractionController? controller;
Timer? touchTimer;
if (_isUsbAttached) {
void triggerTouchPrompt() async {
controller = await _withContext(
(context) async => promptUserInteraction(
context,
icon: const Icon(Icons.touch_app),
title: 'Touch Required',
description: 'Touch the button on your YubiKey now.',
),
);
} }
@override if (credential.touchRequired) {
Future<OathCode> calculate(OathCredential credential, triggerTouchPrompt();
{bool update = true}) async { } else if (credential.oathType == OathType.hotp) {
final OathCode code; touchTimer =
var resultJson = await _api.calculate(credential.id); Timer(const Duration(milliseconds: 500), triggerTouchPrompt);
var result = jsonDecode(resultJson); }
code = OathCode.fromJson(result); }
_log.debug('Calculate', jsonEncode(code));
if (update && mounted) { try {
final creds = state!.toList(); final resultJson = await _methods
final i = creds.indexWhere((e) => e.credential.id == credential.id); .invokeMethod('calculate', {'credentialId': credential.id});
state = creds..[i] = creds[i].copyWith(code: code); _log.debug('Calculate', resultJson);
return OathCode.fromJson(jsonDecode(resultJson));
} on PlatformException catch (pe) {
if (CancellationException.isCancellation(pe)) {
throw CancellationException();
}
rethrow;
} finally {
touchTimer?.cancel();
controller?.close();
} }
return code;
} }
@override @override
Future<OathCredential> addAccount(Uri credentialUri, Future<OathCredential> addAccount(Uri credentialUri,
{bool requireTouch = false}) async { {bool requireTouch = false}) async {
String resultString = try {
await _api.addAccount(credentialUri.toString(), requireTouch); String resultString = await _methods.invokeMethod('addAccount',
{'uri': credentialUri.toString(), 'requireTouch': requireTouch});
var result = jsonDecode(resultString); var result = jsonDecode(resultString);
refresh();
return OathCredential.fromJson(result['credential']); return OathCredential.fromJson(result['credential']);
} on PlatformException catch (pe) {
if (CancellationException.isCancellation(pe)) {
throw CancellationException();
}
_log.error('Failed to add account.', pe);
rethrow;
}
} }
@override @override
Future<OathCredential> renameAccount( Future<OathCredential> renameAccount(
OathCredential credential, String? issuer, String name) async { OathCredential credential, String? issuer, String name) async {
try { try {
String response; final response = await _methods.invokeMethod('renameAccount',
response = await _api.renameAccount(credential.id, name, issuer); {'credentialId': credential.id, 'name': name, 'issuer': issuer});
_log.debug('Rename response: $response');
var responseJson = jsonDecode(response); var responseJson = jsonDecode(response);
var renamedCredential = OathCredential.fromJson(responseJson); return OathCredential.fromJson(responseJson);
} on PlatformException catch (pe) {
if (mounted) { _log.debug('Failed to execute renameOathCredential: ${pe.message}');
final newState = state!.toList(); if (CancellationException.isCancellation(pe)) {
final index = newState.indexWhere((e) => e.credential == credential); throw CancellationException();
final oldPair = newState.removeAt(index);
newState.add(OathPair(
renamedCredential,
oldPair.code,
));
state = newState;
} }
rethrow;
return renamedCredential;
} on PlatformException catch (e) {
_log.debug('Failed to execute renameOathCredential: ${e.message}');
} }
return credential;
} }
@override @override
Future<void> deleteAccount(OathCredential credential) async { Future<void> deleteAccount(OathCredential credential) async {
try { try {
await _api.deleteAccount(credential.id); await _methods
.invokeMethod('deleteAccount', {'credentialId': credential.id});
if (mounted) { } on PlatformException catch (e) {
state = state!.toList()..removeWhere((e) => e.credential == credential); _log.debug('Received exception: $e');
} if (CancellationException.isCancellation(e)) {
} catch (e) { throw CancellationException();
_log.debug('Call to delete credential failed: $e');
}
}
refresh() async {
if (_currentDevice == null) return;
_log.debug('refreshing credentials...');
try {
var resultString = await _api.refreshCodes();
var result = jsonDecode(resultString);
final pairs = result.map((e) => OathPair.fromJson(e)).toList();
if (mounted) {
final current = state?.toList() ?? [];
for (var pair in pairs) {
final i =
current.indexWhere((e) => e.credential.id == pair.credential.id);
if (i < 0) {
current.add(pair);
} else if (pair.code != null) {
current[i] = current[i].copyWith(code: pair.code);
}
}
state = current;
_scheduleRefresh();
}
} catch (e) {
_log.debug('Failure refreshing codes: $e');
}
}
_scheduleRefresh() {
_timer?.cancel();
if (_currentDevice == null) return;
if (state == null) {
_log.debug('No OATH state, refresh immediately');
refresh();
} else if (mounted) {
final expirations = (state ?? [])
.where((pair) =>
pair.credential.oathType == OathType.totp &&
!pair.credential.touchRequired)
.map((e) => e.code)
.whereType<OathCode>()
.map((e) => e.validTo);
if (expirations.isEmpty) {
_log.debug('No expirations, no refresh');
_timer = null;
} else {
final earliest = expirations.reduce(min) * 1000;
final now = DateTime.now().millisecondsSinceEpoch;
if (earliest < now) {
_log.debug('Already expired, refresh immediately');
refresh();
} else {
_log.debug('Schedule refresh in ${earliest - now}ms');
_timer = Timer(Duration(milliseconds: earliest - now), refresh);
}
} }
rethrow;
} }
} }
} }

View File

@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import 'qr_scanner_scan_status.dart';
import 'qr_scanner_util.dart';
/// Return the rounded rect which represents the scanner area for the background
/// overlay and the stroke
RRect _getScannerAreaRRect(Size size) {
double scannerAreaWidth = getScannerAreaWidth(size);
var scannerAreaRect = Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: scannerAreaWidth,
height: scannerAreaWidth);
return RRect.fromRectAndRadius(
scannerAreaRect, const Radius.circular(scannerAreaRadius));
}
// CustomPainter which strokes the scannerArea
class _ScannerAreaStrokePainter extends CustomPainter {
final Color _strokeColor;
_ScannerAreaStrokePainter(this._strokeColor) : super();
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = _strokeColor
..style = PaintingStyle.stroke
..strokeWidth = 3.0;
Path path = Path()..addRRect(_getScannerAreaRRect(size));
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
/// clips the scanner area rounded rect of specific Size
class _ScannerAreaClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
return Path()
..addRect(Rect.fromLTWH(0, 0, size.width, size.height))
..addRRect(_getScannerAreaRRect(size))
..fillType = PathFillType.evenOdd;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => true;
}
class QRScannerOverlay extends StatelessWidget {
final ScanStatus status;
final Size screenSize;
const QRScannerOverlay({
super.key,
required this.status,
required this.screenSize,
});
@override
Widget build(BuildContext context) {
var size = screenSize;
return Stack(children: [
/// clip scanner area "hole" into a darkened background
ClipPath(
clipper: _ScannerAreaClipper(),
child: Opacity(
opacity: 0.6,
child: ColoredBox(
color: Colors.black,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [Spacer()],
)))),
/// draw a stroke around the scanner area
Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CustomPaint(
painter: _ScannerAreaStrokePainter(status == ScanStatus.error
? Colors.red.shade400
: Colors.green.shade400),
),
],
),
/// extra icon when successful scan occurred
if (status == ScanStatus.success)
Positioned.fromRect(
rect: Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: size.width,
height: size.height),
child: Icon(
Icons.check_circle,
size: 200,
color: Colors.green.shade400,
)),
]);
}
}

View File

@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
import 'qr_scanner_scan_status.dart';
import 'qr_scanner_util.dart';
class QRScannerPermissionsUI extends StatelessWidget {
final ScanStatus status;
final Size screenSize;
final Function onPermissionRequest;
const QRScannerPermissionsUI({
super.key,
required this.status,
required this.screenSize,
required this.onPermissionRequest
});
@override
Widget build(BuildContext context) {
var scannerAreaWidth = getScannerAreaWidth(screenSize);
return Stack(children: [
/// instruction text under the scanner area
Positioned.fromRect(
rect: Rect.fromCenter(
center: Offset(screenSize.width / 2,
screenSize.height - scannerAreaWidth / 2.0 + 8.0),
width: screenSize.width,
height: screenSize.height),
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 36),
child: Text(
'Yubico Authenticator needs Camera permissions for scanning QR codes.',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
)),
/// button for manual entry
Positioned.fromRect(
rect: Rect.fromCenter(
center: Offset(screenSize.width / 2, screenSize.height),
width: screenSize.width,
height: screenSize.height),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
const Text(
'Have account info?',
textScaleFactor: 0.7,
style: TextStyle(color: Colors.white),
),
OutlinedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Enter manually',
style: TextStyle(color: Colors.white))),
],
),
Column(
children: [
const Text(
'Would like to scan?',
textScaleFactor: 0.7,
style: TextStyle(color: Colors.white),
),
OutlinedButton(
onPressed: () {
onPermissionRequest();
},
child: const Text('Review permissions',
style: TextStyle(color: Colors.white))),
],
)
]),
),
]);
}
}

View File

@ -0,0 +1,5 @@
/// Status of the scanning process
/// scanning - showing preview and scanning it for finding credential QR code
/// error - a QR code has been found but is not a credential
/// success - a QR code has been found and is a usable credential
enum ScanStatus { scanning, error, success }

View File

@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import 'qr_scanner_scan_status.dart';
import 'qr_scanner_util.dart';
class QRScannerUI extends StatelessWidget {
final ScanStatus status;
final Size screenSize;
const QRScannerUI({
super.key,
required this.status,
required this.screenSize,
});
@override
Widget build(BuildContext context) {
var scannerAreaWidth = getScannerAreaWidth(screenSize);
return Stack(children: [
/// instruction text under the scanner area
Positioned.fromRect(
rect: Rect.fromCenter(
center: Offset(screenSize.width / 2,
screenSize.height + scannerAreaWidth / 2.0 + 8.0),
width: screenSize.width,
height: screenSize.height),
child: Text(
status != ScanStatus.error
? 'Point your camera at a QR code to scan it'
: 'Invalid QR code',
style: const TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
/// button for manual entry
Positioned.fromRect(
rect: Rect.fromCenter(
center: Offset(screenSize.width / 2,
screenSize.height + scannerAreaWidth / 2.0 + 80.0),
width: screenSize.width,
height: screenSize.height),
child: Column(
children: [
const Text(
'No QR code?',
textScaleFactor: 0.7,
style: TextStyle(color: Colors.white),
),
OutlinedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Enter manually',
style: TextStyle(color: Colors.white))),
],
),
),
]);
}
}

View File

@ -0,0 +1,5 @@
import 'dart:ui';
const double scannerAreaRadius = 40.0;
double getScannerAreaWidth(Size size) => size.width - scannerAreaRadius;

Some files were not shown because too many files have changed in this diff Show More