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
Lucas Nogueira 1 year ago committed by GitHub
parent fe79adb5c7
commit 8df28a9875
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,6 @@
---
"biometric": major
"biometric-js": major
---
Initial release.

@ -74,7 +74,6 @@
],
"postversion": "pnpm install --no-frozen-lockfile"
},
"deep-link-example-js": {
"path": "./plugins/deep-link/examples/app",
"manager": "javascript",
@ -82,7 +81,6 @@
"dependencies": ["deep-link-js"],
"postversion": "pnpm install --no-frozen-lockfile"
},
"authenticator": {
"path": "./plugins/authenticator",
"manager": "rust"
@ -91,7 +89,6 @@
"path": "./plugins/authenticator",
"manager": "javascript"
},
"autostart": {
"path": "./plugins/autostart",
"manager": "rust"
@ -100,7 +97,6 @@
"path": "./plugins/autostart",
"manager": "javascript"
},
"barcode-scanner": {
"path": "./plugins/barcode-scanner",
"manager": "rust"
@ -109,7 +105,14 @@
"path": "./plugins/barcode-scanner",
"manager": "javascript"
},
"biometric": {
"path": "./plugins/biometric",
"manager": "rust"
},
"biometric-js": {
"path": "./plugins/biometric",
"manager": "javascript"
},
"cli": {
"path": "./plugins/cli",
"manager": "rust"
@ -118,7 +121,6 @@
"path": "./plugins/cli",
"manager": "javascript"
},
"clipboard-manager": {
"path": "./plugins/clipboard-manager",
"manager": "rust"
@ -127,7 +129,6 @@
"path": "./plugins/clipboard-manager",
"manager": "javascript"
},
"deep-link": {
"path": "./plugins/deep-link",
"manager": "rust"
@ -136,7 +137,6 @@
"path": "./plugins/deep-link",
"manager": "javascript"
},
"fs": {
"path": "./plugins/fs",
"manager": "rust"
@ -145,7 +145,6 @@
"path": "./plugins/fs",
"manager": "javascript"
},
"dialog": {
"path": "./plugins/dialog",
"manager": "rust",
@ -155,7 +154,6 @@
"path": "./plugins/dialog",
"manager": "javascript"
},
"global-shortcut": {
"path": "./plugins/global-shortcut",
"manager": "rust"
@ -164,7 +162,6 @@
"path": "./plugins/global-shortcut",
"manager": "javascript"
},
"http": {
"path": "./plugins/http",
"manager": "rust",
@ -174,12 +171,10 @@
"path": "./plugins/http",
"manager": "javascript"
},
"localhost": {
"path": "./plugins/localhost",
"manager": "rust"
},
"log-plugin": {
"path": "./plugins/log",
"manager": "rust"
@ -206,7 +201,6 @@
"path": "./plugins/notification",
"manager": "javascript"
},
"os": {
"path": "./plugins/os",
"manager": "rust"
@ -215,13 +209,11 @@
"path": "./plugins/os",
"manager": "javascript"
},
"persisted-scope": {
"path": "./plugins/persisted-scope",
"manager": "rust",
"dependencies": ["fs"]
},
"positioner": {
"path": "./plugins/positioner",
"manager": "rust"
@ -230,7 +222,6 @@
"path": "./plugins/positioner",
"manager": "javascript"
},
"process": {
"path": "./plugins/process",
"manager": "rust"
@ -239,7 +230,6 @@
"path": "./plugins/process",
"manager": "javascript"
},
"shell": {
"path": "./plugins/shell",
"manager": "rust"
@ -248,12 +238,10 @@
"path": "./plugins/shell",
"manager": "javascript"
},
"single-instance": {
"path": "./plugins/single-instance",
"manager": "rust"
},
"sql": {
"path": "./plugins/sql",
"manager": "rust",
@ -283,7 +271,6 @@
"path": "./plugins/sql",
"manager": "javascript"
},
"store": {
"path": "./plugins/store",
"manager": "rust"
@ -292,7 +279,6 @@
"path": "./plugins/store",
"manager": "javascript"
},
"stronghold": {
"path": "./plugins/stronghold",
"manager": "rust"
@ -301,7 +287,6 @@
"path": "./plugins/stronghold",
"manager": "javascript"
},
"updater": {
"path": "./plugins/updater",
"manager": "rust"
@ -310,7 +295,6 @@
"path": "./plugins/updater",
"manager": "javascript"
},
"upload": {
"path": "./plugins/upload",
"manager": "rust"
@ -319,7 +303,6 @@
"path": "./plugins/upload",
"manager": "javascript"
},
"websocket": {
"path": "./plugins/websocket",
"manager": "rust"
@ -328,7 +311,6 @@
"path": "./plugins/websocket",
"manager": "javascript"
},
"window-state": {
"path": "./plugins/window-state",
"manager": "rust"

14
Cargo.lock generated

@ -238,6 +238,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-barcode-scanner",
"tauri-plugin-biometric",
"tauri-plugin-cli",
"tauri-plugin-clipboard-manager",
"tauri-plugin-dialog",
@ -5896,6 +5897,19 @@ dependencies = [
"thiserror",
]
[[package]]
name = "tauri-plugin-biometric"
version = "1.0.0"
dependencies = [
"log",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-build",
"thiserror",
]
[[package]]
name = "tauri-plugin-cli"
version = "2.0.0-alpha.5"

@ -11,6 +11,7 @@
"dependencies": {
"@tauri-apps/api": "2.0.0-alpha.12",
"@tauri-apps/plugin-barcode-scanner": "2.0.0-alpha.3",
"@tauri-apps/plugin-biometric": "1.0.0",
"@tauri-apps/plugin-cli": "2.0.0-alpha.4",
"@tauri-apps/plugin-clipboard-manager": "2.0.0-alpha.4",
"@tauri-apps/plugin-dialog": "2.0.0-alpha.4",

@ -48,6 +48,7 @@ tauri-plugin-updater = { path = "../../../plugins/updater", version = "2.0.0-alp
[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]
tauri-plugin-barcode-scanner = { path = "../../../plugins/barcode-scanner/", version = "2.0.0-alpha.3" }
tauri-plugin-nfc = { path = "../../../plugins/nfc", version = "1.0.0" }
tauri-plugin-biometric = { path = "../../../plugins/biometric/", version = "1.0.0" }
[target."cfg(target_os = \"windows\")".dependencies]
window-shadows = "0.2"

@ -15,6 +15,7 @@
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/buildSrc" />
<option value="$PROJECT_DIR$/../../../../../plugins/barcode-scanner/android" />
<option value="$PROJECT_DIR$/../../../../../plugins/biometric/android" />
<option value="$PROJECT_DIR$/../../../../../plugins/clipboard-manager/android" />
<option value="$PROJECT_DIR$/../../../../../plugins/dialog/android" />
<option value="$PROJECT_DIR$/../../../../../plugins/nfc/android" />

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">

@ -44,5 +44,7 @@
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSFaceIDUsageDescription</key>
<string>Biometric Test</string>
</dict>
</plist>

@ -48,6 +48,7 @@ pub fn run() {
{
app.handle().plugin(tauri_plugin_barcode_scanner::init())?;
app.handle().plugin(tauri_plugin_nfc::init())?;
app.handle().plugin(tauri_plugin_biometric::init())?;
}
let mut window_builder = WindowBuilder::new(app, "main", WindowUrl::default());

@ -17,6 +17,7 @@
import Clipboard from "./views/Clipboard.svelte";
import WebRTC from "./views/WebRTC.svelte";
import Scanner from "./views/Scanner.svelte";
import Biometric from "./views/Biometric.svelte";
import { onMount } from "svelte";
import { ask } from "@tauri-apps/plugin-dialog";
@ -113,6 +114,11 @@
component: Nfc,
icon: "i-ph-nfc",
},
isMobile && {
label: "Biometric",
component: Biometric,
icon: "i-ph-scan",
},
];
let selected = views[0];

@ -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 @@
![biometric](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/biometric/banner.png)
<!-- 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);
}
}

@ -0,0 +1,31 @@
<svg class="crabnebula-logo" width="100%" height="100%" viewBox="0 0 1204 210" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
xml:space="preserve" xmlns:serif="http://www.serif.com/"
style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<style>
.crabnebula-logo path,
.crabnebula-logo rect {
fill: #001e42;
}
@media (prefers-color-scheme: dark) {
.crabnebula-logo path, .crabnebula-logo rect {
fill: #fff;
}
}
html[data-color-mode="dark"] .crabnebula-logo path,
html[data-color-mode="dark"] .crabnebula-logo rect {
fill: #fff;
}
</style>
<path d="M351.903,162.334C344.288,162.334 337.123,160.881 330.41,157.975C323.696,155.069 317.834,151.11 312.824,146.099C307.914,141.089 304.006,135.276 301.101,128.662C298.195,121.948 296.742,114.783 296.742,107.167C296.742,99.55 298.195,92.435 301.101,85.821C304.006,79.107 307.914,73.244 312.824,68.234C317.834,63.223 323.696,59.265 330.41,56.358C337.123,53.452 344.288,51.999 351.903,51.999C357.414,51.999 362.675,52.701 367.685,54.103C372.795,55.507 377.455,57.511 381.663,60.116C385.972,62.622 389.83,65.678 393.237,69.286C396.644,72.793 399.499,76.752 401.804,81.161L380.762,92.586C377.756,87.174 373.848,82.915 369.038,79.808C364.328,76.702 358.617,75.148 351.903,75.148C347.494,75.148 343.386,76 339.578,77.704C335.871,79.407 332.614,81.762 329.809,84.769C327.003,87.675 324.798,91.082 323.195,94.991C321.592,98.799 320.79,102.857 320.79,107.167C320.79,111.476 321.592,115.584 323.195,119.493C324.798,123.301 327.003,126.708 329.809,129.715C332.614,132.621 335.871,134.926 339.578,136.629C343.386,138.333 347.494,139.185 351.903,139.185C358.617,139.185 364.328,137.631 369.038,134.525C373.848,131.418 377.756,127.159 380.762,121.748L401.804,133.172C399.499,137.581 396.644,141.59 393.237,145.198C389.83,148.705 385.972,151.762 381.663,154.367C377.455,156.872 372.795,158.827 367.685,160.23C362.675,161.633 357.414,162.334 351.903,162.334Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M413.821,85.37L436.517,85.37L436.517,96.644C437.72,93.337 439.924,90.481 443.131,88.076C446.437,85.671 450.195,84.468 454.403,84.468C455.506,84.468 456.658,84.518 457.86,84.619C459.063,84.719 460.366,84.969 461.768,85.37L461.768,108.369C460.065,107.768 458.412,107.317 456.808,107.016C455.205,106.716 453.502,106.565 451.698,106.565C446.788,106.565 443.03,108.269 440.425,111.676C437.82,115.083 436.517,119.493 436.517,124.904L436.517,160.53L413.821,160.53L413.821,85.37Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M502.161,162.184C497.251,162.184 492.642,161.132 488.333,159.027C484.125,156.923 480.467,154.117 477.361,150.609C474.255,147.001 471.8,142.843 469.996,138.133C468.193,133.322 467.291,128.261 467.291,122.95C467.291,117.639 468.193,112.628 469.996,107.918C471.8,103.108 474.255,98.949 477.361,95.442C480.467,91.834 484.125,88.978 488.333,86.873C492.642,84.769 497.251,83.717 502.161,83.717C504.666,83.717 506.971,84.017 509.075,84.619C511.28,85.12 513.234,85.821 514.937,86.723C516.741,87.625 518.244,88.627 519.446,89.729C520.749,90.832 521.801,91.884 522.603,92.886L522.603,85.37L545.299,85.37L545.299,160.53L522.603,160.53L522.603,153.014C521.801,154.016 520.749,155.069 519.446,156.171C518.244,157.273 516.741,158.275 514.937,159.177C513.234,160.079 511.28,160.781 509.075,161.282C506.971,161.883 504.666,162.184 502.161,162.184ZM507.272,141.59C512.382,141.59 516.49,139.836 519.597,136.329C522.803,132.821 524.406,128.362 524.406,122.95C524.406,117.539 522.803,113.079 519.597,109.572C516.49,106.064 512.382,104.31 507.272,104.31C502.161,104.31 498.003,106.064 494.796,109.572C491.69,113.079 490.137,117.539 490.137,122.95C490.137,128.362 491.69,132.821 494.796,136.329C498.003,139.836 502.161,141.59 507.272,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M607.116,162.184C604.611,162.184 602.256,161.883 600.051,161.282C597.947,160.781 595.993,160.079 594.19,159.177C592.486,158.275 590.983,157.273 589.681,156.171C588.378,155.069 587.376,154.016 586.674,153.014L586.674,160.53L563.979,160.53L563.979,47.79L586.674,47.79L586.674,92.886C587.376,91.884 588.378,90.832 589.681,89.729C590.983,88.627 592.486,87.625 594.19,86.723C595.993,85.821 597.947,85.12 600.051,84.619C602.256,84.017 604.611,83.717 607.116,83.717C612.026,83.717 616.585,84.769 620.793,86.873C625.102,88.978 628.81,91.834 631.916,95.442C635.022,98.949 637.477,103.108 639.281,107.918C641.084,112.628 641.986,117.639 641.986,122.95C641.986,128.261 641.084,133.322 639.281,138.133C637.477,142.843 635.022,147.001 631.916,150.609C628.81,154.117 625.102,156.923 620.793,159.027C616.585,161.132 612.026,162.184 607.116,162.184ZM602.005,141.59C607.116,141.59 611.224,139.836 614.33,136.329C617.537,132.821 619.14,128.362 619.14,122.95C619.14,117.539 617.537,113.079 614.33,109.572C611.224,106.064 607.116,104.31 602.005,104.31C596.895,104.31 592.737,106.064 589.53,109.572C586.424,113.079 584.871,117.539 584.871,122.95C584.871,128.362 586.424,132.821 589.53,136.329C592.737,139.836 596.895,141.59 602.005,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M732.106,160.53L680.101,94.54L680.101,160.53L656.203,160.53L656.203,53.803L676.795,53.803L728.649,119.793L728.649,53.803L752.698,53.803L752.698,160.53L732.106,160.53Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M806.852,162.184C801.341,162.184 796.13,161.282 791.22,159.478C786.411,157.674 782.202,155.069 778.595,151.661C774.988,148.254 772.132,144.145 770.028,139.335C767.923,134.425 766.871,128.963 766.871,122.95C766.871,117.338 767.823,112.177 769.727,107.467C771.731,102.657 774.487,98.498 777.994,94.991C781.601,91.483 785.809,88.727 790.619,86.723C795.429,84.719 800.69,83.717 806.401,83.717C811.311,83.717 816.021,84.518 820.53,86.122C825.139,87.625 829.147,89.93 832.554,93.036C835.961,96.043 838.666,99.851 840.67,104.461C842.775,108.97 843.827,114.282 843.827,120.395C843.827,121.397 843.777,122.549 843.677,123.852C843.677,125.055 843.576,126.558 843.376,128.362L788.816,128.362C789.517,132.871 791.671,136.228 795.279,138.433C798.886,140.538 802.844,141.59 807.153,141.59C811.562,141.59 815.319,140.738 818.425,139.034C821.632,137.231 823.937,135.226 825.339,133.022L842.173,145.649C838.666,150.659 833.857,154.668 827.744,157.674C821.732,160.681 814.768,162.184 806.852,162.184ZM821.281,113.48C820.279,109.471 818.275,106.615 815.269,104.912C812.263,103.108 809.107,102.206 805.8,102.206C804.096,102.206 802.393,102.406 800.69,102.807C798.986,103.208 797.383,103.859 795.88,104.761C794.377,105.663 793.024,106.816 791.822,108.219C790.719,109.622 789.918,111.376 789.417,113.48L821.281,113.48Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M901.265,162.184C898.76,162.184 896.405,161.883 894.201,161.282C892.097,160.781 890.143,160.079 888.339,159.177C886.636,158.275 885.133,157.273 883.83,156.171C882.527,155.069 881.525,154.016 880.824,153.014L880.824,160.53L858.128,160.53L858.128,47.79L880.824,47.79L880.824,92.886C881.525,91.884 882.527,90.832 883.83,89.729C885.133,88.627 886.636,87.625 888.339,86.723C890.143,85.821 892.097,85.12 894.201,84.619C896.405,84.017 898.76,83.717 901.265,83.717C906.175,83.717 910.734,84.769 914.943,86.873C919.252,88.978 922.959,91.834 926.065,95.442C929.172,98.949 931.627,103.108 933.43,107.918C935.234,112.628 936.136,117.639 936.136,122.95C936.136,128.261 935.234,133.322 933.43,138.133C931.627,142.843 929.172,147.001 926.065,150.609C922.959,154.117 919.252,156.923 914.943,159.027C910.734,161.132 906.175,162.184 901.265,162.184ZM896.155,141.59C901.265,141.59 905.374,139.836 908.48,136.329C911.686,132.821 913.29,128.362 913.29,122.95C913.29,117.539 911.686,113.079 908.48,109.572C905.374,106.064 901.265,104.31 896.155,104.31C891.045,104.31 886.886,106.064 883.68,109.572C880.573,113.079 879.02,117.539 879.02,122.95C879.02,128.362 880.573,132.821 883.68,136.329C886.886,139.836 891.045,141.59 896.155,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M977.812,162.184C968.493,162.184 961.429,159.077 956.619,152.864C951.81,146.651 949.405,138.433 949.405,128.211L949.405,85.37L972.101,85.37L972.101,124.303C972.101,129.815 972.952,134.074 974.656,137.08C976.459,140.087 979.466,141.59 983.674,141.59C987.983,141.59 991.39,140.037 993.895,136.93C996.5,133.823 997.803,128.813 997.803,121.898L997.803,85.37L1020.5,85.37L1020.5,160.53L997.803,160.53L997.803,152.864C995.999,155.469 993.444,157.674 990.137,159.478C986.83,161.282 982.722,162.184 977.812,162.184Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<rect x="1039.11" y="47.79" width="22.701" height="112.74" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M1110.86,162.184C1105.95,162.184 1101.34,161.132 1097.03,159.027C1092.83,156.923 1089.17,154.117 1086.06,150.609C1082.96,147.001 1080.5,142.843 1078.7,138.133C1076.89,133.322 1075.99,128.261 1075.99,122.95C1075.99,117.639 1076.89,112.628 1078.7,107.918C1080.5,103.108 1082.96,98.949 1086.06,95.442C1089.17,91.834 1092.83,88.978 1097.03,86.873C1101.34,84.769 1105.95,83.717 1110.86,83.717C1113.37,83.717 1115.67,84.017 1117.78,84.619C1119.98,85.12 1121.94,85.821 1123.64,86.723C1125.44,87.625 1126.95,88.627 1128.15,89.729C1129.45,90.832 1130.5,91.884 1131.3,92.886L1131.3,85.37L1154,85.37L1154,160.53L1131.3,160.53L1131.3,153.014C1130.5,154.016 1129.45,155.069 1128.15,156.171C1126.95,157.273 1125.44,158.275 1123.64,159.177C1121.94,160.079 1119.98,160.781 1117.78,161.282C1115.67,161.883 1113.37,162.184 1110.86,162.184ZM1115.97,141.59C1121.08,141.59 1125.19,139.836 1128.3,136.329C1131.5,132.821 1133.11,128.362 1133.11,122.95C1133.11,117.539 1131.5,113.079 1128.3,109.572C1125.19,106.064 1121.08,104.31 1115.97,104.31C1110.86,104.31 1106.7,106.064 1103.5,109.572C1100.39,113.079 1098.84,117.539 1098.84,122.95C1098.84,128.362 1100.39,132.821 1103.5,136.329C1106.7,139.836 1110.86,141.59 1115.97,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
<path d="M146.48,54.585C119.724,89.866 119.878,134.941 146.826,155.264C153.908,160.605 162.136,163.705 170.903,164.732C146.032,184.934 117.382,191.203 98.037,178.045C71.507,160 72.524,112.249 100.309,71.391C123.51,37.273 158.039,18.749 184.247,24.072C170.404,30.195 157.116,40.561 146.48,54.585ZM181.638,99.643C169.141,111.453 154.859,119.304 142.801,121.916C149.921,147.367 177.29,149.323 177.29,149.323C177.29,149.323 193.578,145.578 205.877,117.941C216.005,95.183 215.122,71.668 204.914,59.7C204.065,71.267 195.731,86.324 181.638,99.643Z" style="stroke:black;stroke-width:0.55px;"/>
</svg>

After

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

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"]
}

@ -1,5 +1,5 @@
{
"$schema": "../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.16/node_modules/@tauri-apps/cli/schema.json",
"$schema": "../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.17/node_modules/@tauri-apps/cli/schema.json",
"build": {
"distDir": ".",
"devPath": "http://localhost:4000"

@ -1,5 +1,5 @@
{
"$schema": "../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.16/node_modules/@tauri-apps/cli/schema.json",
"$schema": "../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.17/node_modules/@tauri-apps/cli/schema.json",
"build": {
"distDir": ".",
"devPath": "http://localhost:4000"

@ -1,5 +1,5 @@
{
"$schema": "../../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.16/node_modules/@tauri-apps/cli/schema.json",
"$schema": "../../../../node_modules/.pnpm/@tauri-apps+cli@2.0.0-alpha.17/node_modules/@tauri-apps/cli/schema.json",
"build": {
"distDir": [],
"devPath": []

@ -69,6 +69,9 @@ importers:
'@tauri-apps/plugin-barcode-scanner':
specifier: 2.0.0-alpha.3
version: link:../../plugins/barcode-scanner
'@tauri-apps/plugin-biometric':
specifier: 1.0.0
version: link:../../plugins/biometric
'@tauri-apps/plugin-cli':
specifier: 2.0.0-alpha.4
version: link:../../plugins/cli
@ -155,6 +158,16 @@ importers:
specifier: 2.0.0-alpha.12
version: 2.0.0-alpha.12
plugins/biometric:
dependencies:
'@tauri-apps/api':
specifier: 2.0.0-alpha.12
version: 2.0.0-alpha.12
devDependencies:
tslib:
specifier: 2.6.0
version: 2.6.0
plugins/cli:
dependencies:
'@tauri-apps/api':

Loading…
Cancel
Save