feat(mobile): add biometric plugin (#829)
* chore: update deps, make mobile script paths relative * feat(biometric): setup plugin folder * feat: implement iOS * add api * android * fix plugin name * also check empty info.plist entry * add example * fix android * supress * lint * better explanation * add partners & contributed by * change ext * license headers * update vite * add covector setup * tauri/dox removed * add example * docs --------- Co-authored-by: Lucas Nogueira <lucas@tauri.app>pull/839/head
parent
fe79adb5c7
commit
8df28a9875
@ -0,0 +1,6 @@
|
||||
---
|
||||
"biometric": major
|
||||
"biometric-js": major
|
||||
---
|
||||
|
||||
Initial release.
|
@ -0,0 +1,30 @@
|
||||
<script>
|
||||
import { authenticate } from "@tauri-apps/plugin-biometric";
|
||||
|
||||
export let onMessage;
|
||||
let allowDeviceCredential = true;
|
||||
|
||||
function auth() {
|
||||
authenticate("Tauri API wants to show it is awesome :)", {
|
||||
allowDeviceCredential,
|
||||
cancelTitle: "Cancel request",
|
||||
fallbackTitle: "Trying the fallback option",
|
||||
title: "Tauri API Auth",
|
||||
subtitle: "Please authenticate :)",
|
||||
confirmationRequired: false,
|
||||
maxAttemps: 1,
|
||||
})
|
||||
.then(onMessage)
|
||||
.catch(onMessage);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<input
|
||||
type="checkbox"
|
||||
id="dllowDeviceCredential"
|
||||
bind:checked={allowDeviceCredential}
|
||||
/>
|
||||
<label for="allowDeviceCredentiale">Allow device credential</label>
|
||||
</div>
|
||||
<button class="btn" id="cli-matches" on:click={auth}> Authenticate </button>
|
@ -0,0 +1 @@
|
||||
/.tauri
|
@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "tauri-plugin-biometric"
|
||||
version = "1.0.0"
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
links = "tauri-plugin-biometric"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustc-args = [ "--cfg", "docsrs" ]
|
||||
rustdoc-args = [ "--cfg", "docsrs" ]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
serde_repr = "0.1"
|
@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
@ -0,0 +1,177 @@
|
||||
|
||||
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
|
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
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.
|
@ -0,0 +1,112 @@
|
||||

|
||||
|
||||
<!-- description -->
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.65**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-biometric = "2.0.0-alpha"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-biometric = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
<!-- Add the branch for installations using git! -->
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-biometric
|
||||
# or
|
||||
npm add @tauri-apps/plugin-biometric
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-biometric
|
||||
|
||||
# alternatively with Git:
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-biometric#v2
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-biometric#v2
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-biometric#v2
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/main.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_biometric::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { authenticate } from "@tauri-apps/plugin-biometric";
|
||||
await authenticate('Open your wallet');
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Contributed By
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="contributors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://impierce.com" target="_blank">
|
||||
<img src="contributors/impierce.svg" alt="Impierce" width="283" height="90">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
@ -0,0 +1,45 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.biometric"
|
||||
compileSdk = 32
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
targetSdk = 32
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.biometric:biometric:1.1.0")
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.0")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
@ -0,0 +1,28 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.biometric
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("app.tauri.biometric", appContext.packageName)
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<activity
|
||||
android:name=".BiometricActivity"
|
||||
android:label="BiometricActivity"
|
||||
android:theme="@style/AppTheme.Transparent"/>
|
||||
</application>
|
||||
</manifest>
|
@ -0,0 +1,129 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.biometric
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.biometrics.BiometricManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import java.util.concurrent.Executor
|
||||
|
||||
class BiometricActivity : AppCompatActivity() {
|
||||
@SuppressLint("WrongConstant")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.auth_activity)
|
||||
|
||||
val executor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
this.mainExecutor
|
||||
} else {
|
||||
Executor { command: Runnable? ->
|
||||
Handler(this.mainLooper).post(
|
||||
command!!
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val builder = BiometricPrompt.PromptInfo.Builder()
|
||||
val intent = intent
|
||||
var title = intent.getStringExtra(BiometricPlugin.TITLE)
|
||||
val subtitle = intent.getStringExtra(BiometricPlugin.SUBTITLE)
|
||||
val description = intent.getStringExtra(BiometricPlugin.REASON)
|
||||
allowDeviceCredential = false
|
||||
// Android docs say we should check if the device is secure before enabling device credential fallback
|
||||
val manager = getSystemService(
|
||||
Context.KEYGUARD_SERVICE
|
||||
) as KeyguardManager
|
||||
if (manager.isDeviceSecure) {
|
||||
allowDeviceCredential =
|
||||
intent.getBooleanExtra(BiometricPlugin.DEVICE_CREDENTIAL, false)
|
||||
}
|
||||
|
||||
if (title.isNullOrEmpty()) {
|
||||
title = "Authenticate"
|
||||
}
|
||||
|
||||
builder.setTitle(title).setSubtitle(subtitle).setDescription(description)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
var authenticators = BiometricManager.Authenticators.BIOMETRIC_WEAK
|
||||
if (allowDeviceCredential) {
|
||||
authenticators = authenticators or BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||
}
|
||||
builder.setAllowedAuthenticators(authenticators)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
builder.setDeviceCredentialAllowed(allowDeviceCredential)
|
||||
}
|
||||
|
||||
// From the Android docs:
|
||||
// You can't call setNegativeButtonText() and setAllowedAuthenticators(... or DEVICE_CREDENTIAL)
|
||||
// at the same time on a BiometricPrompt.PromptInfo.Builder instance.
|
||||
if (!allowDeviceCredential) {
|
||||
val negativeButtonText = intent.getStringExtra(BiometricPlugin.CANCEL_TITLE)
|
||||
builder.setNegativeButtonText(
|
||||
if (negativeButtonText.isNullOrEmpty()) "Cancel" else negativeButtonText
|
||||
)
|
||||
}
|
||||
builder.setConfirmationRequired(
|
||||
intent.getBooleanExtra(BiometricPlugin.CONFIRMATION_REQUIRED, true)
|
||||
)
|
||||
val promptInfo = builder.build()
|
||||
val prompt = BiometricPrompt(
|
||||
this,
|
||||
executor,
|
||||
object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationError(
|
||||
errorCode: Int,
|
||||
errorMessage: CharSequence
|
||||
) {
|
||||
super.onAuthenticationError(errorCode, errorMessage)
|
||||
finishActivity(
|
||||
BiometryResultType.ERROR,
|
||||
errorCode,
|
||||
errorMessage as String
|
||||
)
|
||||
}
|
||||
|
||||
override fun onAuthenticationSucceeded(
|
||||
result: BiometricPrompt.AuthenticationResult
|
||||
) {
|
||||
super.onAuthenticationSucceeded(result)
|
||||
finishActivity()
|
||||
}
|
||||
}
|
||||
)
|
||||
prompt.authenticate(promptInfo)
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun finishActivity(
|
||||
resultType: BiometryResultType = BiometryResultType.SUCCESS,
|
||||
errorCode: Int = 0,
|
||||
errorMessage: String? = ""
|
||||
) {
|
||||
val intent = Intent()
|
||||
val prefix = BiometricPlugin.RESULT_EXTRA_PREFIX
|
||||
intent
|
||||
.putExtra(prefix + BiometricPlugin.RESULT_TYPE, resultType.toString())
|
||||
.putExtra(prefix + BiometricPlugin.RESULT_ERROR_CODE, errorCode)
|
||||
.putExtra(
|
||||
prefix + BiometricPlugin.RESULT_ERROR_MESSAGE,
|
||||
errorMessage
|
||||
)
|
||||
setResult(Activity.RESULT_OK, intent)
|
||||
finish()
|
||||
}
|
||||
|
||||
companion object {
|
||||
var allowDeviceCredential = false
|
||||
}
|
||||
}
|
@ -0,0 +1,253 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.biometric
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.biometric.BiometricManager
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import app.tauri.annotation.ActivityCallback
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSArray
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
import java.util.EnumMap
|
||||
import java.util.HashMap
|
||||
import kotlin.math.max
|
||||
|
||||
enum class BiometryResultType {
|
||||
SUCCESS, FAILURE, ERROR
|
||||
}
|
||||
|
||||
private const val MAX_ATTEMPTS = "maxAttemps"
|
||||
private const val BIOMETRIC_FAILURE = "authenticationFailed"
|
||||
private const val INVALID_CONTEXT_ERROR = "invalidContext"
|
||||
|
||||
@InvokeArg
|
||||
class AuthOptions {
|
||||
lateinit var reason: String
|
||||
var allowDeviceCredential: Boolean = false
|
||||
var title: String? = null
|
||||
var subtitle: String? = null
|
||||
var cancelTitle: String? = null
|
||||
var confirmationRequired: Boolean? = null
|
||||
var maxAttemps: Int = 3
|
||||
}
|
||||
|
||||
@TauriPlugin
|
||||
class BiometricPlugin(private val activity: Activity): Plugin(activity) {
|
||||
private var biometryTypes: ArrayList<BiometryType> = arrayListOf()
|
||||
|
||||
companion object {
|
||||
var RESULT_EXTRA_PREFIX = ""
|
||||
const val TITLE = "title"
|
||||
const val SUBTITLE = "subtitle"
|
||||
const val REASON = "reason"
|
||||
const val CANCEL_TITLE = "cancelTitle"
|
||||
const val RESULT_TYPE = "type"
|
||||
const val RESULT_ERROR_CODE = "errorCode"
|
||||
const val RESULT_ERROR_MESSAGE = "errorMessage"
|
||||
const val DEVICE_CREDENTIAL = "allowDeviceCredential"
|
||||
const val CONFIRMATION_REQUIRED = "confirmationRequired"
|
||||
|
||||
// Maps biometry error numbers to string error codes
|
||||
private var biometryErrorCodeMap: MutableMap<Int, String> = HashMap()
|
||||
private var biometryNameMap: MutableMap<BiometryType, String> = EnumMap(BiometryType::class.java)
|
||||
|
||||
init {
|
||||
biometryErrorCodeMap[BiometricManager.BIOMETRIC_SUCCESS] = ""
|
||||
biometryErrorCodeMap[BiometricManager.BIOMETRIC_SUCCESS] = ""
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_CANCELED] = "systemCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_HW_NOT_PRESENT] = "biometryNotAvailable"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_HW_UNAVAILABLE] = "biometryNotAvailable"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_LOCKOUT] = "biometryLockout"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_LOCKOUT_PERMANENT] = "biometryLockout"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_NEGATIVE_BUTTON] = "userCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_NO_BIOMETRICS] = "biometryNotEnrolled"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL] = "noDeviceCredential"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_NO_SPACE] = "systemCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_TIMEOUT] = "systemCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_UNABLE_TO_PROCESS] = "systemCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_USER_CANCELED] = "userCancel"
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_VENDOR] = "systemCancel"
|
||||
|
||||
biometryNameMap[BiometryType.NONE] = "No Authentication"
|
||||
biometryNameMap[BiometryType.FINGERPRINT] = "Fingerprint Authentication"
|
||||
biometryNameMap[BiometryType.FACE] = "Face Authentication"
|
||||
biometryNameMap[BiometryType.IRIS] = "Iris Authentication"
|
||||
}
|
||||
}
|
||||
|
||||
override fun load(webView: WebView) {
|
||||
super.load(webView)
|
||||
|
||||
biometryTypes = ArrayList()
|
||||
val manager = activity.packageManager
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
|
||||
biometryTypes.add(BiometryType.FINGERPRINT)
|
||||
}
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_FACE)) {
|
||||
biometryTypes.add(BiometryType.FACE)
|
||||
}
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_IRIS)) {
|
||||
biometryTypes.add(BiometryType.IRIS)
|
||||
}
|
||||
if (biometryTypes.size == 0) {
|
||||
biometryTypes.add(BiometryType.NONE)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the device's availability and type of biometric authentication.
|
||||
*/
|
||||
@Command
|
||||
fun getStatus(invoke: Invoke) {
|
||||
val manager = BiometricManager.from(activity)
|
||||
val biometryResult = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
manager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)
|
||||
} else {
|
||||
manager.canAuthenticate()
|
||||
}
|
||||
val ret = JSObject()
|
||||
|
||||
val available = biometryResult == BiometricManager.BIOMETRIC_SUCCESS
|
||||
ret.put(
|
||||
"isAvailable",
|
||||
available
|
||||
)
|
||||
|
||||
ret.put("biometryType", biometryTypes[0].type)
|
||||
|
||||
if (!available) {
|
||||
var reason = ""
|
||||
when (biometryResult) {
|
||||
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> reason =
|
||||
"Biometry unavailable."
|
||||
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> reason =
|
||||
"Biometrics not enrolled."
|
||||
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> reason =
|
||||
"No biometric on this device."
|
||||
BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> reason =
|
||||
"A security update is required."
|
||||
BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> reason =
|
||||
"Unsupported biometry."
|
||||
BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> reason =
|
||||
"Unknown biometry state."
|
||||
}
|
||||
|
||||
var errorCode = biometryErrorCodeMap[biometryResult]
|
||||
if (errorCode == null) {
|
||||
errorCode = "biometryNotAvailable"
|
||||
}
|
||||
ret.put("error", reason)
|
||||
ret.put("errorCode", errorCode)
|
||||
}
|
||||
|
||||
invoke.resolve(ret)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt the user for biometric authentication.
|
||||
*/
|
||||
@Command
|
||||
fun authenticate(invoke: Invoke) {
|
||||
// The result of an intent is supposed to have the package name as a prefix
|
||||
RESULT_EXTRA_PREFIX = activity.packageName + "."
|
||||
val intent = Intent(
|
||||
activity,
|
||||
BiometricActivity::class.java
|
||||
)
|
||||
|
||||
val args = invoke.parseArgs(AuthOptions::class.java)
|
||||
|
||||
// Pass the options to the activity
|
||||
intent.putExtra(
|
||||
TITLE,
|
||||
args.title ?: (biometryNameMap[biometryTypes[0]] ?: "")
|
||||
)
|
||||
intent.putExtra(SUBTITLE, args.subtitle)
|
||||
intent.putExtra(REASON, args.reason)
|
||||
intent.putExtra(CANCEL_TITLE, args.cancelTitle)
|
||||
intent.putExtra(DEVICE_CREDENTIAL, args.allowDeviceCredential)
|
||||
args.confirmationRequired?.let {
|
||||
intent.putExtra(CONFIRMATION_REQUIRED, it)
|
||||
}
|
||||
|
||||
val maxAttemptsConfig = args.maxAttemps
|
||||
val maxAttempts = max(maxAttemptsConfig, 1)
|
||||
intent.putExtra(MAX_ATTEMPTS, maxAttempts)
|
||||
startActivityForResult(invoke, intent, "authenticateResult")
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private fun authenticateResult(invoke: Invoke, result: ActivityResult) {
|
||||
val resultCode = result.resultCode
|
||||
|
||||
// If the system canceled the activity, we might get RESULT_CANCELED in resultCode.
|
||||
// In that case return that immediately, because there won't be any data.
|
||||
if (resultCode == Activity.RESULT_CANCELED) {
|
||||
invoke.reject(
|
||||
"The system canceled authentication",
|
||||
biometryErrorCodeMap[BiometricPrompt.ERROR_CANCELED]
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Convert the string result type to an enum
|
||||
val data = result.data
|
||||
val resultTypeName = data?.getStringExtra(
|
||||
RESULT_EXTRA_PREFIX + RESULT_TYPE
|
||||
)
|
||||
if (resultTypeName == null) {
|
||||
invoke.reject(
|
||||
"Missing data in the result of the activity",
|
||||
INVALID_CONTEXT_ERROR
|
||||
)
|
||||
return
|
||||
}
|
||||
val resultType = try {
|
||||
BiometryResultType.valueOf(resultTypeName)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
invoke.reject(
|
||||
"Invalid data in the result of the activity",
|
||||
INVALID_CONTEXT_ERROR
|
||||
)
|
||||
return
|
||||
}
|
||||
val errorCode = data.getIntExtra(
|
||||
RESULT_EXTRA_PREFIX + RESULT_ERROR_CODE,
|
||||
0
|
||||
)
|
||||
var errorMessage = data.getStringExtra(
|
||||
RESULT_EXTRA_PREFIX + RESULT_ERROR_MESSAGE
|
||||
)
|
||||
when (resultType) {
|
||||
BiometryResultType.SUCCESS -> invoke.resolve()
|
||||
BiometryResultType.FAILURE -> // Biometry was successfully presented but was not recognized
|
||||
invoke.reject(errorMessage, BIOMETRIC_FAILURE)
|
||||
|
||||
BiometryResultType.ERROR -> {
|
||||
// The user cancelled, the system cancelled, or some error occurred.
|
||||
// If the user cancelled, errorMessage is the text of the "negative" button,
|
||||
// which is not especially descriptive.
|
||||
if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) {
|
||||
errorMessage = "Cancel button was pressed"
|
||||
}
|
||||
invoke.reject(errorMessage, biometryErrorCodeMap[errorCode])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal enum class BiometryType(val type: Int) {
|
||||
NONE(0), FINGERPRINT(1), FACE(2), IRIS(3);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context="app.tauri.biometric.BiometricActivity">
|
||||
|
||||
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
@ -0,0 +1,10 @@
|
||||
<resources>
|
||||
<style name="AppTheme.Transparent" parent="Theme.AppCompat.NoActionBar">
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</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>
|
@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.biometric
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::process::exit;
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = tauri_build::mobile::PluginBuilder::new()
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.run()
|
||||
{
|
||||
println!("{error:#}");
|
||||
exit(1);
|
||||
}
|
||||
}
|
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 14 KiB |
@ -0,0 +1,77 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { invoke } from "@tauri-apps/api/primitives";
|
||||
|
||||
export enum BiometryType {
|
||||
None = 0,
|
||||
// Apple TouchID or Android fingerprint
|
||||
TouchID = 1,
|
||||
// Apple FaceID or Android face authentication
|
||||
FaceID = 2,
|
||||
// Android iris authentication
|
||||
Iris = 3,
|
||||
}
|
||||
|
||||
export interface Status {
|
||||
isAvailable: boolean;
|
||||
biometryType: BiometryType;
|
||||
error?: string;
|
||||
errorCode?:
|
||||
| "appCancel"
|
||||
| "authenticationFailed"
|
||||
| "invalidContext"
|
||||
| "notInteractive"
|
||||
| "passcodeNotSet"
|
||||
| "systemCancel"
|
||||
| "userCancel"
|
||||
| "userFallback"
|
||||
| "biometryLockout"
|
||||
| "biometryNotAvailable"
|
||||
| "biometryNotEnrolled";
|
||||
}
|
||||
|
||||
export interface AuthOptions {
|
||||
allowDeviceCredential?: boolean;
|
||||
cancelTitle?: string;
|
||||
|
||||
// iOS options
|
||||
fallbackTitle?: string;
|
||||
|
||||
// android options
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
confirmationRequired?: boolean;
|
||||
maxAttemps?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the biometric authentication is available.
|
||||
* @returns a promise resolving to an object containing all the information about the status of the biometry.
|
||||
*/
|
||||
export async function checkStatus(): Promise<Status> {
|
||||
return invoke("plugin:biometric|status");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompts the user for authentication using the system interface (touchID, faceID or Android Iris).
|
||||
* Rejects if the authentication fails.
|
||||
*
|
||||
* ```javascript
|
||||
* import { authenticate } from "@tauri-apps/plugin-biometric";
|
||||
* await authenticate('Open your wallet');
|
||||
* ```
|
||||
* @param reason
|
||||
* @param options
|
||||
* @returns
|
||||
*/
|
||||
export async function authenticate(
|
||||
reason: string,
|
||||
options?: AuthOptions,
|
||||
): Promise<void> {
|
||||
return invoke("plugin:biometric|authenticate", {
|
||||
reason,
|
||||
...options,
|
||||
});
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
@ -0,0 +1,33 @@
|
||||
// swift-tools-version:5.3
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-biometric",
|
||||
platforms: [
|
||||
.iOS(.v13)
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-biometric",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-biometric"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../.tauri/tauri-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-biometric",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
@ -0,0 +1,3 @@
|
||||
# Tauri Plugin {{ plugin_name_original }}
|
||||
|
||||
A description of this package.
|
@ -0,0 +1,152 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LocalAuthentication
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
class BiometricStatus {
|
||||
let available: Bool
|
||||
let biometryType: LABiometryType
|
||||
let errorReason: String?
|
||||
let errorCode: String?
|
||||
|
||||
init(available: Bool, biometryType: LABiometryType, errorReason: String?, errorCode: String?) {
|
||||
self.available = available
|
||||
self.biometryType = biometryType
|
||||
self.errorReason = errorReason
|
||||
self.errorCode = errorCode
|
||||
}
|
||||
}
|
||||
|
||||
struct AuthOptions: Decodable {
|
||||
let reason: String
|
||||
var allowDeviceCredential: Bool?
|
||||
let fallbackTitle: String?
|
||||
let cancelTitle: String?
|
||||
}
|
||||
|
||||
class BiometricPlugin: Plugin {
|
||||
let authenticationErrorCodeMap: [Int: String] = [
|
||||
0: "",
|
||||
LAError.appCancel.rawValue: "appCancel",
|
||||
LAError.authenticationFailed.rawValue: "authenticationFailed",
|
||||
LAError.invalidContext.rawValue: "invalidContext",
|
||||
LAError.notInteractive.rawValue: "notInteractive",
|
||||
LAError.passcodeNotSet.rawValue: "passcodeNotSet",
|
||||
LAError.systemCancel.rawValue: "systemCancel",
|
||||
LAError.userCancel.rawValue: "userCancel",
|
||||
LAError.userFallback.rawValue: "userFallback",
|
||||
LAError.biometryLockout.rawValue: "biometryLockout",
|
||||
LAError.biometryNotAvailable.rawValue: "biometryNotAvailable",
|
||||
LAError.biometryNotEnrolled.rawValue: "biometryNotEnrolled",
|
||||
]
|
||||
|
||||
var status: BiometricStatus!
|
||||
|
||||
public override func load(webview: WKWebView) {
|
||||
let context = LAContext()
|
||||
var error: NSError?
|
||||
var available = context.canEvaluatePolicy(
|
||||
.deviceOwnerAuthenticationWithBiometrics, error: &error)
|
||||
var reason: String? = nil
|
||||
var errorCode: String? = nil
|
||||
|
||||
if available && context.biometryType == .faceID {
|
||||
let entry = Bundle.main.infoDictionary?["NSFaceIDUsageDescription"] as? String
|
||||
|
||||
if entry == nil || entry?.count == 0 {
|
||||
available = false
|
||||
reason = "NSFaceIDUsageDescription is not in the app Info.plist"
|
||||
errorCode = authenticationErrorCodeMap[LAError.biometryNotAvailable.rawValue] ?? ""
|
||||
}
|
||||
} else if !available, let error = error {
|
||||
reason = error.localizedDescription
|
||||
if let failureReason = error.localizedFailureReason {
|
||||
reason = "\(reason ?? ""): \(failureReason)"
|
||||
}
|
||||
errorCode =
|
||||
authenticationErrorCodeMap[error.code] ?? authenticationErrorCodeMap[
|
||||
LAError.biometryNotAvailable.rawValue] ?? ""
|
||||
}
|
||||
|
||||
self.status = BiometricStatus(
|
||||
available: available,
|
||||
biometryType: context.biometryType,
|
||||
errorReason: reason,
|
||||
errorCode: errorCode
|
||||
)
|
||||
}
|
||||
|
||||
@objc func status(_ invoke: Invoke) {
|
||||
if self.status.available {
|
||||
invoke.resolve([
|
||||
"isAvailable": self.status.available,
|
||||
"biometryType": self.status.biometryType.rawValue,
|
||||
])
|
||||
} else {
|
||||
invoke.resolve([
|
||||
"isAvailable": self.status.available,
|
||||
"biometryType": self.status.biometryType.rawValue,
|
||||
"error": self.status.errorReason ?? "",
|
||||
"errorCode": self.status.errorCode ?? "",
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@objc func authenticate(_ invoke: Invoke) throws {
|
||||
guard self.status.available else {
|
||||
invoke.reject(
|
||||
self.status.errorReason ?? "",
|
||||
code: self.status.errorCode ?? ""
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let args = try invoke.parseArgs(AuthOptions.self)
|
||||
|
||||
let context = LAContext()
|
||||
context.localizedFallbackTitle = args.fallbackTitle
|
||||
context.localizedCancelTitle = args.cancelTitle
|
||||
context.touchIDAuthenticationAllowableReuseDuration = 0
|
||||
|
||||
let allowDeviceCredential = args.allowDeviceCredential ?? false
|
||||
|
||||
// force system default fallback title if an empty string is provided (the OS hides the fallback button in this case)
|
||||
if allowDeviceCredential,
|
||||
let fallbackTitle = context.localizedFallbackTitle,
|
||||
fallbackTitle.isEmpty
|
||||
{
|
||||
context.localizedFallbackTitle = nil
|
||||
}
|
||||
|
||||
context.evaluatePolicy(
|
||||
allowDeviceCredential
|
||||
? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics,
|
||||
localizedReason: args.reason
|
||||
) { success, error in
|
||||
if success {
|
||||
invoke.resolve()
|
||||
} else {
|
||||
if let policyError = error as? LAError {
|
||||
let code = self.authenticationErrorCodeMap[policyError.code.rawValue]
|
||||
invoke.reject(policyError.localizedDescription, code: code)
|
||||
} else {
|
||||
invoke.reject(
|
||||
"Unknown error",
|
||||
code: self.authenticationErrorCodeMap[LAError.authenticationFailed.rawValue]
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_biometric")
|
||||
func initPlugin() -> Plugin {
|
||||
return BiometricPlugin()
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import XCTest
|
||||
@testable import ExamplePlugin
|
||||
|
||||
final class ExamplePluginTests: XCTestCase {
|
||||
func testExample() throws {
|
||||
let plugin = ExamplePlugin()
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-biometric",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT or APACHE-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"!dist-js/**/*.map",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"devDependencies": {
|
||||
"tslib": "2.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.0.0-alpha.12"
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from "../../shared/rollup.config.js";
|
||||
|
||||
export default createConfig();
|
@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_BIOMETRIC__=function(e){"use strict";async function n(e,n={},r){return window.__TAURI_INTERNALS__.invoke(e,n,r)}var r;return"function"==typeof SuppressedError&&SuppressedError,e.BiometryType=void 0,(r=e.BiometryType||(e.BiometryType={}))[r.None=0]="None",r[r.TouchID=1]="TouchID",r[r.FaceID=2]="FaceID",r[r.Iris=3]="Iris",e.authenticate=async function(e,r){return n("plugin:biometric|authenticate",{reason:e,...r})},e.checkStatus=async function(){return n("plugin:biometric|status")},e}({});Object.defineProperty(window.__TAURI__,"biometric",{value:__TAURI_PLUGIN_BIOMETRIC__})}
|
@ -0,0 +1,25 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#![cfg(mobile)]
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri::{
|
||||
plugin::{Builder, PluginHandle, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
pub use models::*;
|
||||
|
||||
mod error;
|
||||
mod models;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "app.tauri.biometric";
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
tauri::ios_plugin_binding!(init_plugin_biometric);
|
||||
|
||||
/// Access to the biometric APIs.
|
||||
pub struct Biometric<R: Runtime>(PluginHandle<R>);
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AuthenticatePayload {
|
||||
reason: String,
|
||||
#[serde(flatten)]
|
||||
options: AuthOptions,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Biometric<R> {
|
||||
pub fn status(&self) -> crate::Result<Status> {
|
||||
self.0.run_mobile_plugin("status", ()).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn authenticate(&self, reason: String, options: AuthOptions) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("authenticate", AuthenticatePayload { reason, options })
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the biometric APIs.
|
||||
pub trait BiometricExt<R: Runtime> {
|
||||
fn biometric(&self) -> &Biometric<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> crate::BiometricExt<R> for T {
|
||||
fn biometric(&self) -> &Biometric<R> {
|
||||
self.state::<Biometric<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin.
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
Builder::new("biometric")
|
||||
.js_init_script(include_str!("api-iife.js").to_string())
|
||||
.setup(|app, api| {
|
||||
#[cfg(target_os = "android")]
|
||||
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "BiometricPlugin")?;
|
||||
#[cfg(target_os = "ios")]
|
||||
let handle = api.register_ios_plugin(init_plugin_biometric)?;
|
||||
app.manage(Biometric(handle));
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthOptions {
|
||||
pub allow_device_credential: bool,
|
||||
/// iOS only.
|
||||
pub fallback_title: Option<String>,
|
||||
/// iOS only.
|
||||
pub cancel_title: Option<String>,
|
||||
/// Android only.
|
||||
pub title: Option<String>,
|
||||
/// Android only.
|
||||
pub subtitle: Option<String>,
|
||||
/// Android only.
|
||||
pub confirmation_required: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde_repr::Deserialize_repr)]
|
||||
#[repr(u8)]
|
||||
pub enum BiometryType {
|
||||
None = 0,
|
||||
TouchID = 1,
|
||||
FaceID = 2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Status {
|
||||
pub is_available: bool,
|
||||
pub biometry_type: BiometryType,
|
||||
pub error: Option<String>,
|
||||
pub error_code: Option<String>,
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
Loading…
Reference in new issue