@secure-signing/react-native 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/android/build.gradle +26 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/expo/modules/securesigner/SecureKeyStore.kt +203 -0
- package/android/src/main/java/expo/modules/securesigner/SecureSignerModule.kt +212 -0
- package/android/src/main/java/expo/modules/securesigner/SignerPolicy.kt +197 -0
- package/app.plugin.js +1 -0
- package/build/encoding.d.ts +11 -0
- package/build/encoding.js +71 -0
- package/build/encoding.js.map +1 -0
- package/build/errors.d.ts +16 -0
- package/build/errors.js +65 -0
- package/build/errors.js.map +1 -0
- package/build/index.d.ts +11 -0
- package/build/index.js +28 -0
- package/build/index.js.map +1 -0
- package/build/signer.d.ts +17 -0
- package/build/signer.js +210 -0
- package/build/signer.js.map +1 -0
- package/build/types.d.ts +114 -0
- package/build/types.js +11 -0
- package/build/types.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/SecureSignerCore.swift +192 -0
- package/ios/SecureSignerModule.swift +403 -0
- package/ios/SecureSigning.podspec +30 -0
- package/ios/Tests/SecureSignerCoreTests.swift +143 -0
- package/package.json +63 -4
- package/plugin/build/index.d.ts +14 -0
- package/plugin/build/index.js +31 -0
- package/src/encoding.ts +65 -0
- package/src/errors.ts +66 -0
- package/src/index.ts +46 -0
- package/src/signer.ts +241 -0
- package/src/types.ts +123 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 secure-signing contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,155 @@
|
|
|
1
|
-
#
|
|
1
|
+
# secure-signing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Hardware-backed, biometric-gated **transaction signing** for Expo and React Native apps.
|
|
4
|
+
|
|
5
|
+
| Package | Use |
|
|
6
|
+
|---|---|
|
|
7
|
+
| [`@secure-signing/react-native`](https://github.com/olukayode-oluseyi/secure-signing/tree/main/packages/react-native) | The app side: an Expo module (works in Expo development builds, EAS Build, and bare React Native with `npx install-expo-modules`) |
|
|
8
|
+
| [`@secure-signing/server`](https://github.com/olukayode-oluseyi/secure-signing/tree/main/packages/server) | The server side: verifier, payload format, Android attestation check, approval flow (Node 22.6+) |
|
|
9
|
+
|
|
10
|
+
- P-256 keys generated inside the **Secure Enclave** (iOS) or **Android Keystore** (TEE, StrongBox when available). The private key never leaves the hardware.
|
|
11
|
+
- **Every** signature requires a fresh biometric match. There is no reuse window and no way to turn authentication off.
|
|
12
|
+
- You sign server-created bytes and get back a DER ECDSA signature. Your server verifies it with the companion `@secure-signing/server` package.
|
|
13
|
+
- **Android key attestation**, so your server can verify that a key really is hardware-backed instead of trusting the client.
|
|
14
|
+
|
|
15
|
+
Use it for payout approval, step-up authentication, high-risk account changes and device binding.
|
|
16
|
+
|
|
17
|
+
> ⚠️ **Android status (0.1.0):** the Android code compiles and passes unit tests in CI, but has **not yet been run on a real device or emulator**. iOS is verified on an iPhone (see [device results](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/TESTING.md#device-results)). Test on your own Android devices before relying on it, and please [report](https://github.com/olukayode-oluseyi/secure-signing/issues) what you find.
|
|
18
|
+
|
|
19
|
+
> ⚠️ **Does not run in Expo Go.** Use a [development build](https://docs.expo.dev/develop/development-builds/introduction/) (`npx expo run:ios` / `run:android`) or EAS Build.
|
|
20
|
+
|
|
21
|
+
| | |
|
|
22
|
+
|---|---|
|
|
23
|
+
| Algorithm | `ECDSA-P256-SHA256` |
|
|
24
|
+
| Public key | `spki-der-base64` (DER SubjectPublicKeyInfo) |
|
|
25
|
+
| Signature | `ecdsa-der-base64` (DER `SEQUENCE { r, s }`) |
|
|
26
|
+
| Payload | exact bytes; strings are UTF-8, not normalized; ≤ 16 KiB |
|
|
27
|
+
| iOS | 16.4+ (Expo SDK 58 minimum), Secure Enclave devices |
|
|
28
|
+
| Android | API 24+; StrongBox on API 28+ devices that have it; strong-biometric key binding on API 30+. **Not yet verified on a device** (see the note above) |
|
|
29
|
+
| Expo | SDK 58+ (React Native 0.88), New Architecture |
|
|
30
|
+
|
|
31
|
+
- [Specification](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/SPEC.md)
|
|
32
|
+
- [Threat model](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/THREAT_MODEL.md)
|
|
33
|
+
- [Server verification and key lifecycle](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/SERVER.md)
|
|
34
|
+
- [Testing tiers](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/TESTING.md)
|
|
35
|
+
- [Changelog](https://github.com/olukayode-oluseyi/secure-signing/blob/main/CHANGELOG.md) · [Contributing](https://github.com/olukayode-oluseyi/secure-signing/blob/main/CONTRIBUTING.md)
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npx expo install @secure-signing/react-native
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`app.json`:
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"expo": {
|
|
48
|
+
"plugins": [["@secure-signing/react-native", { "faceIDPermission": "Use Face ID to approve payouts." }]]
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Then rebuild: `npx expo prebuild` (or `npx expo run:ios|android`, or `eas build`). The plugin:
|
|
54
|
+
|
|
55
|
+
- sets iOS `NSFaceIDUsageDescription`. Pass `faceIDPermission: false` if another plugin sets it.
|
|
56
|
+
- adds Android `USE_BIOMETRIC`.
|
|
57
|
+
|
|
58
|
+
It is idempotent and safe to run repeatedly.
|
|
59
|
+
|
|
60
|
+
## API
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import * as Signer from '@secure-signing/react-native';
|
|
64
|
+
|
|
65
|
+
await Signer.isAvailable(); // false in Expo Go, on web, and on devices without secure hardware + biometrics
|
|
66
|
+
await Signer.getCapabilities(); // { platform, secureEnclaveAvailable, strongBoxAvailable, biometricAuthenticationAvailable, biometricAuthenticationEnrolled, deviceSecure }
|
|
67
|
+
|
|
68
|
+
const info = await Signer.createKey({
|
|
69
|
+
keyId: 'payout-approval-v1', // /^[A-Za-z0-9._-]{1,64}$/, required
|
|
70
|
+
authPolicy: 'biometry-current-set', // default; or 'biometry-any'
|
|
71
|
+
hardware: 'strongbox-preferred', // default; or 'strongbox-required' | 'secure-hardware'
|
|
72
|
+
attestationChallenge: serverNonce, // Android: embeds the nonce in the attestation certificate
|
|
73
|
+
// allowNonHardwareKey: true, // emulators/simulators ONLY
|
|
74
|
+
});
|
|
75
|
+
// info: { keyId, publicKey, algorithm, publicKeyEncoding, signatureEncoding,
|
|
76
|
+
// authPolicy, hardwareBacked: boolean | 'unknown', securityLevel, attestation }
|
|
77
|
+
|
|
78
|
+
const { signature } = await Signer.sign({
|
|
79
|
+
keyId: 'payout-approval-v1',
|
|
80
|
+
payload: serverPayloadText, // string (UTF-8) or Uint8Array; never an object
|
|
81
|
+
promptMessage: 'Send NGN 125,000 to acct_9f2c',
|
|
82
|
+
promptTitle: 'Approve payout', // optional (Android)
|
|
83
|
+
cancelLabel: 'Cancel', // optional
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
await Signer.getKeyInfo(keyId); // KeyInfo | null (attestation is always null here)
|
|
87
|
+
await Signer.hasKey(keyId);
|
|
88
|
+
await Signer.deleteKey(keyId); // idempotent
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
There is no default key, no "list keys", no private-key export, no generic crypto API, and no software fallback unless you opt in with `allowNonHardwareKey`.
|
|
92
|
+
|
|
93
|
+
### Errors
|
|
94
|
+
|
|
95
|
+
Every failure is a `SecureSignerError` with a stable `code`. `platformCode` and `message` are informational only.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
try { await Signer.sign(...) } catch (e) {
|
|
99
|
+
if (Signer.isSecureSignerError(e)) switch (e.code) {
|
|
100
|
+
case 'AUTHENTICATION_CANCELLED': /* user backed out */ break;
|
|
101
|
+
case 'AUTHENTICATION_FAILED': /* no match */ break;
|
|
102
|
+
case 'AUTHENTICATION_LOCKED_OUT': /* too many attempts */ break;
|
|
103
|
+
case 'KEY_INVALIDATED': /* biometrics changed → delete + re-enroll via server step-up */ break;
|
|
104
|
+
case 'KEY_NOT_FOUND': /* reinstall / reset → re-enroll */ break;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Full list: `NOT_AVAILABLE, BIOMETRICS_UNAVAILABLE, BIOMETRICS_NOT_ENROLLED, PASSCODE_NOT_SET, AUTHENTICATION_CANCELLED, AUTHENTICATION_FAILED, AUTHENTICATION_LOCKED_OUT, AUTHENTICATION_IN_PROGRESS, KEY_NOT_FOUND, KEY_ALREADY_EXISTS, KEY_INVALIDATED, SECURE_HARDWARE_UNAVAILABLE, STRONGBOX_UNAVAILABLE, DEVICE_LOCKED, ACTIVITY_UNAVAILABLE, INVALID_ARGUMENT, PAYLOAD_TOO_LARGE, SIGNING_FAILED, UNKNOWN`. See [SPEC §5](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/SPEC.md#5-error-contract).
|
|
110
|
+
|
|
111
|
+
Platform notes:
|
|
112
|
+
|
|
113
|
+
- **Android:** a single non-matching fingerprint does not end the prompt. The user can retry until success, cancel or lockout.
|
|
114
|
+
- **iOS:** `AUTHENTICATION_FAILED` is terminal after the system's retry limit.
|
|
115
|
+
|
|
116
|
+
## Enrollment flow
|
|
117
|
+
|
|
118
|
+
1. The user authenticates to your server with step-up (password + OTP, or approval from an existing device).
|
|
119
|
+
2. The server issues a single-use `challenge`.
|
|
120
|
+
3. The app calls `createKey({ keyId, attestationChallenge: challenge })`.
|
|
121
|
+
4. The app sends `publicKey`, `keyId` and `attestation` to the server.
|
|
122
|
+
5. The server checks the key is P-256 (`parsePublicKey`). On Android it runs `verifyAndroidKeyAttestation` against Google's roots. It then binds `keyId` to the user and device.
|
|
123
|
+
|
|
124
|
+
## Payout approval flow
|
|
125
|
+
|
|
126
|
+
1. The server creates the payout as **pending** and builds the payload with `buildPayoutApprovalPayload` (domain-separated, nonce, 5-minute expiry). It stores the exact bytes.
|
|
127
|
+
2. The app receives the payload text and **parses it** (`@secure-signing/server/payload`) to show the amount and destination. Never display separate API fields.
|
|
128
|
+
3. The app calls `sign({ keyId, payload, promptMessage })`.
|
|
129
|
+
4. The server runs `approvePayout`, which checks:
|
|
130
|
+
- session
|
|
131
|
+
- key ownership
|
|
132
|
+
- pending status
|
|
133
|
+
- exact bytes
|
|
134
|
+
- expiry
|
|
135
|
+
- signature
|
|
136
|
+
- single-use nonce
|
|
137
|
+
- atomic approval
|
|
138
|
+
|
|
139
|
+
It then stores the payload and signature for audit.
|
|
140
|
+
|
|
141
|
+
A full runnable flow is in [`example/`](https://github.com/olukayode-oluseyi/secure-signing/tree/main/example).
|
|
142
|
+
|
|
143
|
+
## What a signature does and does not prove
|
|
144
|
+
|
|
145
|
+
It proves that someone passed a biometric check on the enrolled device and that its secure hardware signed **these bytes**.
|
|
146
|
+
|
|
147
|
+
It does **not** prove the user saw the right amount. The UI is drawn by your app, and a rooted or jailbroken device can change what is shown. See the [threat model](https://github.com/olukayode-oluseyi/secure-signing/blob/main/docs/THREAT_MODEL.md).
|
|
148
|
+
|
|
149
|
+
## Security
|
|
150
|
+
|
|
151
|
+
Report vulnerabilities privately: see [SECURITY.md](https://github.com/olukayode-oluseyi/secure-signing/blob/main/SECURITY.md) (GitHub private vulnerability reporting, or `security@deepstacked.dev`).
|
|
152
|
+
|
|
153
|
+
## License
|
|
154
|
+
|
|
155
|
+
MIT. See [LICENSE](https://github.com/olukayode-oluseyi/secure-signing/blob/main/LICENSE).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
plugins {
|
|
2
|
+
id 'com.android.library'
|
|
3
|
+
id 'expo-module-gradle-plugin'
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
group = 'expo.modules.securesigner'
|
|
7
|
+
version = '0.1.0'
|
|
8
|
+
|
|
9
|
+
android {
|
|
10
|
+
namespace "expo.modules.securesigner"
|
|
11
|
+
defaultConfig {
|
|
12
|
+
versionCode 1
|
|
13
|
+
versionName "0.1.0"
|
|
14
|
+
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
dependencies {
|
|
19
|
+
implementation 'androidx.biometric:biometric:1.1.0'
|
|
20
|
+
implementation 'androidx.fragment:fragment-ktx:1.8.5'
|
|
21
|
+
|
|
22
|
+
testImplementation 'junit:junit:4.13.2'
|
|
23
|
+
|
|
24
|
+
androidTestImplementation 'androidx.test:runner:1.6.2'
|
|
25
|
+
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
|
|
26
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
package expo.modules.securesigner
|
|
2
|
+
|
|
3
|
+
import android.app.KeyguardManager
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.pm.PackageManager
|
|
6
|
+
import android.os.Build
|
|
7
|
+
import android.security.keystore.KeyGenParameterSpec
|
|
8
|
+
import android.security.keystore.KeyInfo
|
|
9
|
+
import android.security.keystore.KeyPermanentlyInvalidatedException
|
|
10
|
+
import android.security.keystore.KeyProperties
|
|
11
|
+
import android.util.Base64
|
|
12
|
+
import androidx.biometric.BiometricManager
|
|
13
|
+
import java.security.KeyFactory
|
|
14
|
+
import java.security.KeyPairGenerator
|
|
15
|
+
import java.security.KeyStore
|
|
16
|
+
import java.security.PrivateKey
|
|
17
|
+
import java.security.ProviderException
|
|
18
|
+
import java.security.Signature
|
|
19
|
+
import java.security.spec.ECGenParameterSpec
|
|
20
|
+
|
|
21
|
+
data class KeyDescription(
|
|
22
|
+
val keyId: String,
|
|
23
|
+
val publicKeySpki: ByteArray,
|
|
24
|
+
val authPolicy: AuthPolicy,
|
|
25
|
+
val hardwareBacked: Boolean?,
|
|
26
|
+
val securityLevel: SecurityLevelName,
|
|
27
|
+
val attestationChain: List<ByteArray>?,
|
|
28
|
+
) {
|
|
29
|
+
fun toMap(): Map<String, Any?> = mapOf(
|
|
30
|
+
"keyId" to keyId,
|
|
31
|
+
"publicKey" to Base64.encodeToString(publicKeySpki, Base64.NO_WRAP),
|
|
32
|
+
"authPolicy" to authPolicy.value,
|
|
33
|
+
"hardwareBacked" to (hardwareBacked ?: "unknown"),
|
|
34
|
+
"securityLevel" to securityLevel.value,
|
|
35
|
+
"attestationChain" to attestationChain?.map { Base64.encodeToString(it, Base64.NO_WRAP) },
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Android Keystore operations, independent of Expo and of any UI so they can be
|
|
41
|
+
* exercised by instrumented tests. Private keys never leave the Keystore: only
|
|
42
|
+
* handles (PrivateKey / Signature) are used, and they are never serialized.
|
|
43
|
+
*/
|
|
44
|
+
class SecureKeyStore(private val context: Context) {
|
|
45
|
+
private val keyStore: KeyStore by lazy { KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } }
|
|
46
|
+
|
|
47
|
+
val hasStrongBox: Boolean
|
|
48
|
+
get() = Build.VERSION.SDK_INT >= 28 &&
|
|
49
|
+
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
|
50
|
+
|
|
51
|
+
val isDeviceSecure: Boolean
|
|
52
|
+
get() = (context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager).isDeviceSecure
|
|
53
|
+
|
|
54
|
+
fun biometricStatus(): Int =
|
|
55
|
+
BiometricManager.from(context).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)
|
|
56
|
+
|
|
57
|
+
fun requireBiometricsReady() {
|
|
58
|
+
if (!isDeviceSecure) throw SignerException(SignerErrorCode.PASSCODE_NOT_SET, "device has no screen lock")
|
|
59
|
+
SignerPolicy.mapCanAuthenticate(biometricStatus())?.let { throw it }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
fun hasKey(keyId: String): Boolean {
|
|
63
|
+
SignerPolicy.requireValidKeyId(keyId)
|
|
64
|
+
return keyStore.containsAlias(SignerPolicy.alias(keyId))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
fun deleteKey(keyId: String) {
|
|
68
|
+
SignerPolicy.requireValidKeyId(keyId)
|
|
69
|
+
val alias = SignerPolicy.alias(keyId)
|
|
70
|
+
if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
fun createKey(
|
|
74
|
+
keyId: String,
|
|
75
|
+
policy: AuthPolicy,
|
|
76
|
+
pref: HardwarePreference,
|
|
77
|
+
attestationChallenge: ByteArray?,
|
|
78
|
+
allowNonHardwareKey: Boolean,
|
|
79
|
+
): KeyDescription {
|
|
80
|
+
SignerPolicy.requireValidKeyId(keyId)
|
|
81
|
+
val alias = SignerPolicy.alias(keyId)
|
|
82
|
+
if (keyStore.containsAlias(alias)) {
|
|
83
|
+
throw SignerException(SignerErrorCode.KEY_ALREADY_EXISTS, "a key already exists for this keyId")
|
|
84
|
+
}
|
|
85
|
+
requireBiometricsReady()
|
|
86
|
+
|
|
87
|
+
val plan = SignerPolicy.strongBoxPlan(pref, Build.VERSION.SDK_INT, hasStrongBox)
|
|
88
|
+
var usedStrongBox = plan != StrongBoxPlan.TEE_ONLY
|
|
89
|
+
try {
|
|
90
|
+
generate(alias, policy, usedStrongBox, attestationChallenge)
|
|
91
|
+
} catch (e: ProviderException) {
|
|
92
|
+
val strongBoxMissing = Build.VERSION.SDK_INT >= 28 &&
|
|
93
|
+
e is android.security.keystore.StrongBoxUnavailableException
|
|
94
|
+
when {
|
|
95
|
+
strongBoxMissing && plan == StrongBoxPlan.STRONGBOX_THEN_TEE -> {
|
|
96
|
+
usedStrongBox = false
|
|
97
|
+
generate(alias, policy, false, attestationChallenge)
|
|
98
|
+
}
|
|
99
|
+
strongBoxMissing -> throw SignerException(
|
|
100
|
+
SignerErrorCode.STRONGBOX_UNAVAILABLE, "StrongBox is not available on this device", "StrongBoxUnavailableException", e,
|
|
101
|
+
)
|
|
102
|
+
else -> throw SignerException(SignerErrorCode.UNKNOWN, "key generation failed", e.javaClass.simpleName, e)
|
|
103
|
+
}
|
|
104
|
+
} catch (e: SignerException) {
|
|
105
|
+
throw e
|
|
106
|
+
} catch (e: Exception) {
|
|
107
|
+
throw SignerException(SignerErrorCode.UNKNOWN, "key generation failed", e.javaClass.simpleName, e)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
val description = describe(keyId, usedStrongBox, includeAttestation = attestationChallenge != null)
|
|
112
|
+
?: throw SignerException(SignerErrorCode.UNKNOWN, "generated key not found")
|
|
113
|
+
SignerPolicy.enforceGeneratedKey(description.securityLevel, description.hardwareBacked, pref, allowNonHardwareKey)
|
|
114
|
+
return description
|
|
115
|
+
} catch (e: Exception) {
|
|
116
|
+
// Never leave behind a key that failed our requirements.
|
|
117
|
+
runCatching { keyStore.deleteEntry(alias) }
|
|
118
|
+
throw e
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private fun generate(alias: String, policy: AuthPolicy, strongBox: Boolean, challenge: ByteArray?) {
|
|
123
|
+
val builder = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
|
|
124
|
+
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
|
|
125
|
+
.setDigests(KeyProperties.DIGEST_SHA256)
|
|
126
|
+
.setUserAuthenticationRequired(true)
|
|
127
|
+
.setInvalidatedByBiometricEnrollment(policy == AuthPolicy.BIOMETRY_CURRENT_SET)
|
|
128
|
+
if (Build.VERSION.SDK_INT >= 30) {
|
|
129
|
+
// 0 seconds = authentication required for every use, strong biometrics only.
|
|
130
|
+
builder.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
|
|
131
|
+
} else {
|
|
132
|
+
// -1 = every use must be authorized through BiometricPrompt + CryptoObject (biometric only).
|
|
133
|
+
@Suppress("DEPRECATION")
|
|
134
|
+
builder.setUserAuthenticationValidityDurationSeconds(-1)
|
|
135
|
+
}
|
|
136
|
+
if (Build.VERSION.SDK_INT >= 28) {
|
|
137
|
+
builder.setUnlockedDeviceRequired(true)
|
|
138
|
+
if (strongBox) builder.setIsStrongBoxBacked(true)
|
|
139
|
+
}
|
|
140
|
+
if (challenge != null) builder.setAttestationChallenge(challenge)
|
|
141
|
+
|
|
142
|
+
val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
|
|
143
|
+
kpg.initialize(builder.build())
|
|
144
|
+
kpg.generateKeyPair()
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Returns null if no key exists. [createdWithStrongBox] only matters below API 31. */
|
|
148
|
+
fun describe(keyId: String, createdWithStrongBox: Boolean = false, includeAttestation: Boolean = false): KeyDescription? {
|
|
149
|
+
SignerPolicy.requireValidKeyId(keyId)
|
|
150
|
+
val alias = SignerPolicy.alias(keyId)
|
|
151
|
+
val privateKey = keyStore.getKey(alias, null) as? PrivateKey ?: return null
|
|
152
|
+
val cert = keyStore.getCertificate(alias)
|
|
153
|
+
?: throw SignerException(SignerErrorCode.UNKNOWN, "public key certificate missing")
|
|
154
|
+
val info = KeyFactory.getInstance(privateKey.algorithm, ANDROID_KEYSTORE)
|
|
155
|
+
.getKeySpec(privateKey, KeyInfo::class.java)
|
|
156
|
+
|
|
157
|
+
if (!info.isUserAuthenticationRequired) {
|
|
158
|
+
// Defense in depth: refuse to use any key under our prefix that does not require auth.
|
|
159
|
+
throw SignerException(SignerErrorCode.KEY_INVALIDATED, "key does not require user authentication; delete and re-enroll")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
val level: Int? = if (Build.VERSION.SDK_INT >= 31) info.securityLevel else null
|
|
163
|
+
@Suppress("DEPRECATION")
|
|
164
|
+
val inside = info.isInsideSecureHardware
|
|
165
|
+
val chain = if (includeAttestation) keyStore.getCertificateChain(alias)?.map { it.encoded } else null
|
|
166
|
+
|
|
167
|
+
return KeyDescription(
|
|
168
|
+
keyId = keyId,
|
|
169
|
+
publicKeySpki = cert.publicKey.encoded, // X.509 SubjectPublicKeyInfo DER
|
|
170
|
+
authPolicy = if (info.isInvalidatedByBiometricEnrollment) AuthPolicy.BIOMETRY_CURRENT_SET else AuthPolicy.BIOMETRY_ANY,
|
|
171
|
+
hardwareBacked = SignerPolicy.hardwareBacked(level, inside),
|
|
172
|
+
securityLevel = SignerPolicy.classify(level, inside, createdWithStrongBox),
|
|
173
|
+
attestationChain = chain,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Returns a Signature initialized for signing. It cannot produce a signature
|
|
179
|
+
* until the user authenticates through BiometricPrompt with this object.
|
|
180
|
+
*/
|
|
181
|
+
fun initSignature(keyId: String): Signature {
|
|
182
|
+
SignerPolicy.requireValidKeyId(keyId)
|
|
183
|
+
val privateKey = keyStore.getKey(SignerPolicy.alias(keyId), null) as? PrivateKey
|
|
184
|
+
?: throw SignerException(SignerErrorCode.KEY_NOT_FOUND, "no key exists for this keyId")
|
|
185
|
+
try {
|
|
186
|
+
return Signature.getInstance(SIGNATURE_ALGORITHM).apply { initSign(privateKey) }
|
|
187
|
+
} catch (e: KeyPermanentlyInvalidatedException) {
|
|
188
|
+
throw SignerException(
|
|
189
|
+
SignerErrorCode.KEY_INVALIDATED, "biometric enrollment changed; the key is no longer usable", "KeyPermanentlyInvalidatedException", e,
|
|
190
|
+
)
|
|
191
|
+
} catch (e: Exception) {
|
|
192
|
+
if (Build.VERSION.SDK_INT >= 28 && e.javaClass.simpleName == "UnlockedDeviceRequiredException") {
|
|
193
|
+
throw SignerException(SignerErrorCode.DEVICE_LOCKED, "device is locked", e.javaClass.simpleName, e)
|
|
194
|
+
}
|
|
195
|
+
throw SignerException(SignerErrorCode.SIGNING_FAILED, "could not initialize signing", e.javaClass.simpleName, e)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
companion object {
|
|
200
|
+
const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
|
201
|
+
const val SIGNATURE_ALGORITHM = "SHA256withECDSA" // DER-encoded output
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
package expo.modules.securesigner
|
|
2
|
+
|
|
3
|
+
import android.util.Base64
|
|
4
|
+
import androidx.biometric.BiometricManager
|
|
5
|
+
import androidx.biometric.BiometricPrompt
|
|
6
|
+
import androidx.core.content.ContextCompat
|
|
7
|
+
import androidx.fragment.app.FragmentActivity
|
|
8
|
+
import expo.modules.kotlin.Promise
|
|
9
|
+
import expo.modules.kotlin.modules.Module
|
|
10
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
11
|
+
import expo.modules.kotlin.records.Field
|
|
12
|
+
import expo.modules.kotlin.records.Record
|
|
13
|
+
import java.security.SignatureException
|
|
14
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
15
|
+
|
|
16
|
+
class CreateKeyArgs : Record {
|
|
17
|
+
@Field val keyId: String = ""
|
|
18
|
+
@Field val authPolicy: String = "biometry-current-set"
|
|
19
|
+
@Field val hardware: String = "strongbox-preferred"
|
|
20
|
+
@Field val attestationChallenge: String? = null
|
|
21
|
+
@Field val allowNonHardwareKey: Boolean = false
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class SignArgs : Record {
|
|
25
|
+
@Field val keyId: String = ""
|
|
26
|
+
@Field val payload: String = ""
|
|
27
|
+
@Field val promptMessage: String = ""
|
|
28
|
+
@Field val promptTitle: String = ""
|
|
29
|
+
@Field val cancelLabel: String = "Cancel"
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
class SecureSignerModule : Module() {
|
|
33
|
+
private val signInFlight = AtomicBoolean(false)
|
|
34
|
+
|
|
35
|
+
private val store: SecureKeyStore
|
|
36
|
+
get() = SecureKeyStore(
|
|
37
|
+
appContext.reactContext
|
|
38
|
+
?: throw SignerException(SignerErrorCode.NOT_AVAILABLE, "React context is not available"),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
override fun definition() = ModuleDefinition {
|
|
42
|
+
Name("SecureSigner")
|
|
43
|
+
|
|
44
|
+
AsyncFunction("isAvailable") {
|
|
45
|
+
val s = store
|
|
46
|
+
val status = s.biometricStatus()
|
|
47
|
+
// Hardware present (enrolled or not). Keystore itself is always present on API 24+.
|
|
48
|
+
status == BiometricManager.BIOMETRIC_SUCCESS || status == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
AsyncFunction("getCapabilities") {
|
|
52
|
+
val s = store
|
|
53
|
+
val status = s.biometricStatus()
|
|
54
|
+
mapOf(
|
|
55
|
+
"platform" to "android",
|
|
56
|
+
"secureEnclaveAvailable" to false,
|
|
57
|
+
"strongBoxAvailable" to s.hasStrongBox,
|
|
58
|
+
"biometricAuthenticationAvailable" to
|
|
59
|
+
(status == BiometricManager.BIOMETRIC_SUCCESS || status == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED),
|
|
60
|
+
"biometricAuthenticationEnrolled" to (status == BiometricManager.BIOMETRIC_SUCCESS),
|
|
61
|
+
"deviceSecure" to s.isDeviceSecure,
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
AsyncFunction("createKey") { args: CreateKeyArgs, promise: Promise ->
|
|
66
|
+
run(promise) {
|
|
67
|
+
val challenge = args.attestationChallenge?.let { decodeBase64(it, "attestationChallenge") }
|
|
68
|
+
if (challenge != null && (challenge.isEmpty() || challenge.size > SignerPolicy.MAX_CHALLENGE_BYTES)) {
|
|
69
|
+
throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "attestationChallenge has invalid length")
|
|
70
|
+
}
|
|
71
|
+
store.createKey(
|
|
72
|
+
args.keyId,
|
|
73
|
+
AuthPolicy.from(args.authPolicy),
|
|
74
|
+
HardwarePreference.from(args.hardware),
|
|
75
|
+
challenge,
|
|
76
|
+
args.allowNonHardwareKey,
|
|
77
|
+
).toMap()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
AsyncFunction("getKeyInfo") { keyId: String, promise: Promise ->
|
|
82
|
+
run(promise) { store.describe(keyId)?.toMap() }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
AsyncFunction("hasKey") { keyId: String, promise: Promise ->
|
|
86
|
+
run(promise) { store.hasKey(keyId) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
AsyncFunction("deleteKey") { keyId: String, promise: Promise ->
|
|
90
|
+
run(promise) {
|
|
91
|
+
store.deleteKey(keyId)
|
|
92
|
+
null
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
AsyncFunction("sign") { args: SignArgs, promise: Promise ->
|
|
97
|
+
sign(args, promise)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private fun run(promise: Promise, body: () -> Any?) {
|
|
102
|
+
try {
|
|
103
|
+
promise.resolve(body())
|
|
104
|
+
} catch (e: SignerException) {
|
|
105
|
+
promise.reject(e.code.value, e.jsMessage, null)
|
|
106
|
+
} catch (e: Exception) {
|
|
107
|
+
// Do not forward raw platform messages; they are not part of the contract.
|
|
108
|
+
promise.reject(SignerErrorCode.UNKNOWN.value, "unexpected error [platform:${e.javaClass.simpleName}]", null)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private fun decodeBase64(value: String, name: String): ByteArray {
|
|
113
|
+
val bytes = try {
|
|
114
|
+
Base64.decode(value, Base64.NO_WRAP)
|
|
115
|
+
} catch (e: IllegalArgumentException) {
|
|
116
|
+
throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "$name is not valid base64")
|
|
117
|
+
}
|
|
118
|
+
// Reject non-canonical encodings so the signed bytes are unambiguous.
|
|
119
|
+
if (Base64.encodeToString(bytes, Base64.NO_WRAP) != value) {
|
|
120
|
+
throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "$name is not canonical base64")
|
|
121
|
+
}
|
|
122
|
+
return bytes
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private fun sign(args: SignArgs, promise: Promise) {
|
|
126
|
+
val payload: ByteArray
|
|
127
|
+
val keyStore: SecureKeyStore
|
|
128
|
+
try {
|
|
129
|
+
SignerPolicy.requireValidKeyId(args.keyId)
|
|
130
|
+
if (args.promptMessage.isBlank()) throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "promptMessage is required")
|
|
131
|
+
payload = decodeBase64(args.payload, "payload")
|
|
132
|
+
if (payload.isEmpty()) throw SignerException(SignerErrorCode.INVALID_ARGUMENT, "payload must be non-empty")
|
|
133
|
+
if (payload.size > SignerPolicy.MAX_PAYLOAD_BYTES) throw SignerException(SignerErrorCode.PAYLOAD_TOO_LARGE, "payload is too large")
|
|
134
|
+
keyStore = store
|
|
135
|
+
} catch (e: SignerException) {
|
|
136
|
+
promise.reject(e.code.value, e.jsMessage, null)
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!signInFlight.compareAndSet(false, true)) {
|
|
141
|
+
promise.reject(SignerErrorCode.AUTHENTICATION_IN_PROGRESS.value, "another signing operation is in progress", null)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
val done = AtomicBoolean(false)
|
|
145
|
+
val finish: (Result<String>) -> Unit = finish@{ result ->
|
|
146
|
+
if (!done.compareAndSet(false, true)) return@finish
|
|
147
|
+
signInFlight.set(false)
|
|
148
|
+
result.fold(
|
|
149
|
+
onSuccess = { promise.resolve(mapOf("signature" to it)) },
|
|
150
|
+
onFailure = { e ->
|
|
151
|
+
val se = e as? SignerException
|
|
152
|
+
?: SignerException(SignerErrorCode.UNKNOWN, "unexpected error", e.javaClass.simpleName)
|
|
153
|
+
promise.reject(se.code.value, se.jsMessage, null)
|
|
154
|
+
},
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
try {
|
|
159
|
+
val activity = appContext.currentActivity as? FragmentActivity
|
|
160
|
+
?: throw SignerException(SignerErrorCode.ACTIVITY_UNAVAILABLE, "no foreground FragmentActivity to host the biometric prompt")
|
|
161
|
+
// Key existence and invalidation are checked before prompting, so the user is never asked to authenticate for a dead key.
|
|
162
|
+
val signature = keyStore.initSignature(args.keyId)
|
|
163
|
+
keyStore.requireBiometricsReady()
|
|
164
|
+
|
|
165
|
+
val callback = object : BiometricPrompt.AuthenticationCallback() {
|
|
166
|
+
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
|
167
|
+
val authorized = result.cryptoObject?.signature
|
|
168
|
+
if (authorized == null) {
|
|
169
|
+
finish(Result.failure(SignerException(SignerErrorCode.SIGNING_FAILED, "authentication was not bound to the signing operation")))
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
authorized.update(payload)
|
|
174
|
+
val der = authorized.sign()
|
|
175
|
+
finish(Result.success(Base64.encodeToString(der, Base64.NO_WRAP)))
|
|
176
|
+
} catch (e: SignatureException) {
|
|
177
|
+
finish(Result.failure(SignerException(SignerErrorCode.SIGNING_FAILED, "signing failed", e.javaClass.simpleName, e)))
|
|
178
|
+
} catch (e: Exception) {
|
|
179
|
+
finish(Result.failure(SignerException(SignerErrorCode.SIGNING_FAILED, "signing failed", e.javaClass.simpleName, e)))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
|
184
|
+
finish(Result.failure(SignerPolicy.mapPromptError(errorCode)))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// A single non-matching attempt is not terminal; the prompt stays open until success, cancel or lockout.
|
|
188
|
+
override fun onAuthenticationFailed() = Unit
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
val title = args.promptTitle.ifBlank { args.promptMessage }
|
|
192
|
+
val infoBuilder = BiometricPrompt.PromptInfo.Builder()
|
|
193
|
+
.setTitle(title)
|
|
194
|
+
.setNegativeButtonText(args.cancelLabel.ifBlank { "Cancel" })
|
|
195
|
+
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
|
|
196
|
+
.setConfirmationRequired(true)
|
|
197
|
+
if (title != args.promptMessage) infoBuilder.setDescription(args.promptMessage)
|
|
198
|
+
val info = infoBuilder.build()
|
|
199
|
+
|
|
200
|
+
activity.runOnUiThread {
|
|
201
|
+
try {
|
|
202
|
+
BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), callback)
|
|
203
|
+
.authenticate(info, BiometricPrompt.CryptoObject(signature))
|
|
204
|
+
} catch (e: Exception) {
|
|
205
|
+
finish(Result.failure(SignerException(SignerErrorCode.UNKNOWN, "could not show biometric prompt", e.javaClass.simpleName, e)))
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
} catch (e: Exception) {
|
|
209
|
+
finish(Result.failure(e))
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|