@qntx/wallet-native 0.12.0 → 0.14.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.
Files changed (135) hide show
  1. package/README.md +184 -31
  2. package/WalletNative.podspec +11 -2
  3. package/android/CMakeLists.txt +7 -1
  4. package/android/build.gradle +4 -0
  5. package/android/src/main/AndroidManifest.xml +1 -2
  6. package/android/src/main/cpp/cpp-adapter.cpp +9 -0
  7. package/android/src/main/java/com/margelo/nitro/qntxwallet/CardReader.kt +316 -0
  8. package/android/src/main/java/com/margelo/nitro/qntxwallet/HybridGoogleDriveAuth.kt +142 -0
  9. package/android/src/main/java/com/margelo/nitro/qntxwallet/HybridSecureInputView.kt +25 -0
  10. package/android/src/main/java/com/margelo/nitro/qntxwallet/Keystore.kt +148 -9
  11. package/android/src/main/java/com/margelo/nitro/qntxwallet/SecureInputField.kt +422 -0
  12. package/android/src/main/java/com/margelo/nitro/qntxwallet/VaultAnchor.kt +90 -0
  13. package/android/src/main/java/com/margelo/nitro/qntxwallet/WalletNativePackage.java +10 -0
  14. package/cpp/host/CardReader.hpp +70 -0
  15. package/cpp/host/HybridKernelHost.cpp +90 -15
  16. package/cpp/host/HybridKernelHost.hpp +21 -5
  17. package/cpp/host/KernelFile.cpp +79 -15
  18. package/cpp/host/KernelFile.hpp +17 -6
  19. package/cpp/host/KernelSlot.hpp +103 -0
  20. package/cpp/host/Keystore.hpp +35 -11
  21. package/cpp/host/Lifecycle.cpp +11 -0
  22. package/cpp/host/Lifecycle.hpp +3 -0
  23. package/cpp/host/Passkey.hpp +8 -0
  24. package/cpp/host/SecureInput.cpp +233 -0
  25. package/cpp/host/SecureInput.hpp +103 -0
  26. package/cpp/host/VaultAnchor.cpp +39 -0
  27. package/cpp/host/VaultAnchor.hpp +28 -0
  28. package/cpp/host/VaultDirectory.hpp +1 -1
  29. package/cpp/platform/CardReaderAndroid.cpp +146 -0
  30. package/cpp/platform/CardReaderIos.mm +318 -0
  31. package/cpp/platform/KeystoreAndroid.cpp +48 -1
  32. package/cpp/platform/KeystoreIos.mm +109 -19
  33. package/cpp/platform/PasskeyAndroid.cpp +2 -0
  34. package/cpp/platform/PasskeyIos.mm +20 -18
  35. package/cpp/platform/QntxSecureInputField.h +24 -0
  36. package/cpp/platform/SecureInputAndroid.cpp +110 -0
  37. package/cpp/platform/SecureInputIos.mm +282 -0
  38. package/cpp/platform/VaultAnchorAndroid.cpp +76 -0
  39. package/cpp/platform/VaultAnchorIos.mm +76 -0
  40. package/cpp/runtime/KernelBackends.cpp +35 -28
  41. package/cpp/runtime/KernelBuffer.hpp +2 -5
  42. package/cpp/runtime/KernelCardReader.cpp +385 -0
  43. package/cpp/runtime/KernelCardReader.hpp +27 -0
  44. package/cpp/runtime/KernelGlobals.cpp +176 -63
  45. package/cpp/runtime/KernelGlobals.hpp +13 -7
  46. package/cpp/runtime/KernelJs.cpp +14 -0
  47. package/cpp/runtime/KernelJs.hpp +4 -0
  48. package/cpp/runtime/KernelKeystore.cpp +78 -2
  49. package/cpp/runtime/KernelKeystore.hpp +1 -0
  50. package/cpp/runtime/KernelPasskey.cpp +15 -12
  51. package/cpp/runtime/KernelRuntime.cpp +24 -7
  52. package/cpp/runtime/KernelRuntime.hpp +14 -6
  53. package/cpp/runtime/KernelSecureInput.cpp +154 -0
  54. package/cpp/runtime/KernelSecureInput.hpp +25 -0
  55. package/cpp/runtime/platform/KernelArgon2.cpp +34 -0
  56. package/cpp/runtime/platform/KernelArgon2.hpp +23 -0
  57. package/cpp/vendor/argon2/LICENSE +314 -0
  58. package/cpp/vendor/argon2/README.md +20 -0
  59. package/cpp/vendor/argon2/include/argon2.h +437 -0
  60. package/cpp/vendor/argon2/src/argon2.c +452 -0
  61. package/cpp/vendor/argon2/src/blake2/blake2-impl.h +156 -0
  62. package/cpp/vendor/argon2/src/blake2/blake2.h +89 -0
  63. package/cpp/vendor/argon2/src/blake2/blake2b.c +390 -0
  64. package/cpp/vendor/argon2/src/blake2/blamka-round-ref.h +56 -0
  65. package/cpp/vendor/argon2/src/core.c +648 -0
  66. package/cpp/vendor/argon2/src/core.h +228 -0
  67. package/cpp/vendor/argon2/src/encoding.c +463 -0
  68. package/cpp/vendor/argon2/src/encoding.h +57 -0
  69. package/cpp/vendor/argon2/src/ref.c +194 -0
  70. package/cpp/vendor/argon2/src/thread.c +57 -0
  71. package/cpp/vendor/argon2/src/thread.h +67 -0
  72. package/dist/cloud.d.mts +58 -0
  73. package/dist/cloud.mjs +114 -0
  74. package/dist/cloud.mjs.map +1 -0
  75. package/dist/index.d.mts +13 -4
  76. package/dist/index.mjs +89 -14
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/secure-input.d.mts +24 -0
  79. package/dist/secure-input.mjs +25 -0
  80. package/dist/secure-input.mjs.map +1 -0
  81. package/ios/HybridCloudKitStore.swift +159 -0
  82. package/ios/HybridSecureInputView.swift +35 -0
  83. package/ios/cloud/CloudKitEnvelopeStore.swift +179 -0
  84. package/kernel/generated/kernel-entry.js +51913 -20526
  85. package/kernel/generated/kernel.manifest.json +17 -7
  86. package/nitrogen/generated/android/WalletNative+autolinking.cmake +7 -1
  87. package/nitrogen/generated/android/WalletNativeOnLoad.cpp +37 -2
  88. package/nitrogen/generated/android/c++/JFunc_void_SecureInputState.hpp +77 -0
  89. package/nitrogen/generated/android/c++/JHybridGoogleDriveAuthSpec.cpp +82 -0
  90. package/nitrogen/generated/android/c++/JHybridGoogleDriveAuthSpec.hpp +64 -0
  91. package/nitrogen/generated/android/c++/JHybridSecureInputViewSpec.cpp +70 -0
  92. package/nitrogen/generated/android/c++/JHybridSecureInputViewSpec.hpp +64 -0
  93. package/nitrogen/generated/android/c++/JSecureInputState.hpp +64 -0
  94. package/nitrogen/generated/android/c++/views/JHybridSecureInputViewStateUpdater.cpp +74 -0
  95. package/nitrogen/generated/android/c++/views/JHybridSecureInputViewStateUpdater.hpp +54 -0
  96. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/Func_void_SecureInputState.kt +78 -0
  97. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/HybridGoogleDriveAuthSpec.kt +61 -0
  98. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/HybridSecureInputViewSpec.kt +67 -0
  99. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/SecureInputState.kt +25 -0
  100. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/views/HybridSecureInputViewManager.kt +96 -0
  101. package/nitrogen/generated/android/kotlin/com/margelo/nitro/qntxwallet/views/HybridSecureInputViewStateUpdater.kt +23 -0
  102. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Bridge.cpp +74 -1
  103. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Bridge.hpp +252 -3
  104. package/nitrogen/generated/ios/WalletNative-Swift-Cxx-Umbrella.hpp +21 -3
  105. package/nitrogen/generated/ios/WalletNativeAutolinking.mm +17 -1
  106. package/nitrogen/generated/ios/WalletNativeAutolinking.swift +22 -0
  107. package/nitrogen/generated/ios/c++/HybridCloudKitStoreSpecSwift.cpp +11 -0
  108. package/nitrogen/generated/ios/c++/HybridCloudKitStoreSpecSwift.hpp +116 -0
  109. package/nitrogen/generated/ios/c++/HybridSecureInputViewSpecSwift.cpp +11 -0
  110. package/nitrogen/generated/ios/c++/HybridSecureInputViewSpecSwift.hpp +83 -0
  111. package/nitrogen/generated/ios/c++/views/HybridSecureInputViewComponent.mm +144 -0
  112. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  113. package/nitrogen/generated/ios/swift/Func_void_SecureInputState.swift +46 -0
  114. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  115. package/nitrogen/generated/ios/swift/Func_void_std__optional_std__string_.swift +53 -0
  116. package/nitrogen/generated/ios/swift/Func_void_std__vector_std__string_.swift +46 -0
  117. package/nitrogen/generated/ios/swift/HybridCloudKitStoreSpec.swift +59 -0
  118. package/nitrogen/generated/ios/swift/HybridCloudKitStoreSpec_cxx.swift +230 -0
  119. package/nitrogen/generated/ios/swift/HybridSecureInputViewSpec.swift +55 -0
  120. package/nitrogen/generated/ios/swift/HybridSecureInputViewSpec_cxx.swift +164 -0
  121. package/nitrogen/generated/ios/swift/SecureInputState.swift +48 -0
  122. package/nitrogen/generated/shared/c++/HybridCloudKitStoreSpec.cpp +25 -0
  123. package/nitrogen/generated/shared/c++/HybridCloudKitStoreSpec.hpp +70 -0
  124. package/nitrogen/generated/shared/c++/HybridGoogleDriveAuthSpec.cpp +22 -0
  125. package/nitrogen/generated/shared/c++/HybridGoogleDriveAuthSpec.hpp +64 -0
  126. package/nitrogen/generated/shared/c++/HybridKernelHostSpec.cpp +1 -0
  127. package/nitrogen/generated/shared/c++/HybridKernelHostSpec.hpp +1 -0
  128. package/nitrogen/generated/shared/c++/HybridSecureInputViewSpec.cpp +22 -0
  129. package/nitrogen/generated/shared/c++/HybridSecureInputViewSpec.hpp +65 -0
  130. package/nitrogen/generated/shared/c++/SecureInputState.hpp +84 -0
  131. package/nitrogen/generated/shared/c++/views/HybridSecureInputViewComponent.cpp +34 -0
  132. package/nitrogen/generated/shared/c++/views/HybridSecureInputViewComponent.hpp +85 -0
  133. package/nitrogen/generated/shared/json/SecureInputViewConfig.json +10 -0
  134. package/package.json +24 -6
  135. package/scripts/compile-kernel.mjs +7 -3
@@ -0,0 +1,316 @@
1
+ package com.margelo.nitro.qntxwallet
2
+
3
+ import android.app.Activity
4
+ import android.app.Dialog
5
+ import android.nfc.NfcAdapter
6
+ import android.nfc.Tag
7
+ import android.nfc.tech.IsoDep
8
+ import android.os.Build
9
+ import android.os.Handler
10
+ import android.os.Looper
11
+ import android.text.method.ScrollingMovementMethod
12
+ import android.view.View
13
+ import android.view.ViewGroup
14
+ import android.widget.Button
15
+ import android.widget.LinearLayout
16
+ import android.widget.TextView
17
+ import androidx.annotation.Keep
18
+ import com.facebook.proguard.annotations.DoNotStrip
19
+ import com.margelo.nitro.NitroModules
20
+ import java.io.IOException
21
+ import java.util.concurrent.Executors
22
+
23
+ /**
24
+ * The module's own trusted card surface: reader mode has no system UI (A3), so
25
+ * open() shows a CardSheet carrying the kernel's prompt and a Cancel button
26
+ * while NFC reader mode polls for the card. Session logic runs on a single
27
+ * worker thread; the dialog and reader-mode switches run on the main thread.
28
+ * Status ints are the CardReaderStatus contract shared with
29
+ * CardReaderAndroid.cpp. Prompts, APDUs and responses are never logged.
30
+ */
31
+ @DoNotStrip
32
+ @Keep
33
+ object CardReader {
34
+ private const val OK = 0
35
+ private const val CANCELLED = 1
36
+ private const val TAG_LOST = 3
37
+ private const val INTERRUPTED = 4
38
+ private const val UNAVAILABLE = 5
39
+
40
+ // qntx cards are ISO 14443-A; NDEF and the platform sound are noise (A6).
41
+ private const val READER_FLAGS =
42
+ NfcAdapter.FLAG_READER_NFC_A or
43
+ NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK or
44
+ NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS
45
+
46
+ // protocol.md §16.6: the card's slowest command may take 1.5 s on the wire.
47
+ private const val ISO_DEP_TIMEOUT_MS = 5000
48
+
49
+ // How long the kernel's closing text stays up before the sheet dismisses.
50
+ private const val END_TEXT_DELAY_MS = 1500L
51
+
52
+ private val main = Handler(Looper.getMainLooper())
53
+ private val worker = Executors.newSingleThreadExecutor()
54
+
55
+ // Touched on `worker` only. `session` is the live session; `ended` is the
56
+ // status a dead session left for the next transmit (host contract).
57
+ private var session: Session? = null
58
+ private var endedStatus = UNAVAILABLE
59
+ private var endedDetail: String? = null
60
+
61
+ // `closed` and `sheet` cross the worker/main boundary; the rest is
62
+ // worker-only.
63
+ private class Session(
64
+ val token: Long,
65
+ val activity: Activity,
66
+ val adapter: NfcAdapter,
67
+ ) {
68
+ @Volatile var sheet: CardSheet? = null
69
+ var isoDep: IsoDep? = null
70
+ var txToken: Long = -1L
71
+ var readerOn = false
72
+ @Volatile var closed = false
73
+ }
74
+
75
+ @JvmStatic
76
+ fun open(token: Long, prompt: String) {
77
+ worker.execute {
78
+ if (session != null) {
79
+ // The kernel serializes opens; keep the completion contract anyway.
80
+ return@execute nativeComplete(token, UNAVAILABLE, null, "android:busy")
81
+ }
82
+ val activity = NitroModules.applicationContext?.currentActivity
83
+ ?: return@execute nativeComplete(token, UNAVAILABLE, null, "android:no-activity")
84
+ val adapter = NfcAdapter.getDefaultAdapter(activity)
85
+ ?: return@execute nativeComplete(token, UNAVAILABLE, null, "android:no-nfc")
86
+ if (!adapter.isEnabled) {
87
+ return@execute nativeComplete(token, UNAVAILABLE, null, "android:nfc-disabled")
88
+ }
89
+ endedStatus = UNAVAILABLE
90
+ endedDetail = null
91
+ // The session record exists before the sheet so a close() queued
92
+ // behind this open cannot slip past it.
93
+ val session = Session(token, activity, adapter)
94
+ this@CardReader.session = session
95
+ main.post {
96
+ if (session.closed || activity.isFinishing || activity.isDestroyed) {
97
+ return@post // closed sessions are already settled; a dead
98
+ // activity can never show the sheet
99
+ }
100
+ val sheet = CardSheet(activity)
101
+ session.sheet = sheet
102
+ sheet.onCancel = { worker.execute { endSession(session, CANCELLED, null) } }
103
+ sheet.onFocusChange = { hasFocus ->
104
+ worker.execute {
105
+ if (this@CardReader.session !== session || session.closed) return@execute
106
+ if (hasFocus) {
107
+ if (!session.readerOn) {
108
+ session.readerOn = true
109
+ main.post {
110
+ if (session.closed) return@post
111
+ adapter.enableReaderMode(
112
+ activity,
113
+ { tag -> worker.execute { onTag(session, tag) } },
114
+ READER_FLAGS,
115
+ null,
116
+ )
117
+ }
118
+ }
119
+ } else {
120
+ // An overlay or the pause of the activity took the window's
121
+ // focus: the surface is no longer trusted (A7), so the session
122
+ // ends before another APDU could run uncovered.
123
+ endSession(session, INTERRUPTED, "android:focus-lost")
124
+ }
125
+ }
126
+ }
127
+ sheet.showPrompt(prompt)
128
+ sheet.show()
129
+ if (session.closed) dismissSheet(session)
130
+ }
131
+ }
132
+ }
133
+
134
+ @JvmStatic
135
+ fun transmit(token: Long, apdu: ByteArray) {
136
+ worker.execute {
137
+ val session = session
138
+ if (session == null) {
139
+ // A session end with no transmit in flight fails the next transmit
140
+ // with the end's status (CardReader.hpp contract).
141
+ return@execute nativeComplete(token, endedStatus, null, endedDetail)
142
+ }
143
+ val isoDep = session.isoDep
144
+ if (isoDep == null || session.txToken >= 0) {
145
+ return@execute nativeComplete(token, UNAVAILABLE, null, "android:busy")
146
+ }
147
+ session.txToken = token
148
+ try {
149
+ val response = isoDep.transceive(apdu)
150
+ session.txToken = -1L
151
+ nativeComplete(token, OK, response, null)
152
+ } catch (e: IOException) {
153
+ endSession(session, TAG_LOST, detailOf(e))
154
+ } catch (e: SecurityException) {
155
+ endSession(session, TAG_LOST, detailOf(e))
156
+ }
157
+ }
158
+ }
159
+
160
+ @JvmStatic
161
+ fun close(success: Boolean, text: String) {
162
+ worker.execute {
163
+ val session = session ?: return@execute
164
+ this@CardReader.session = null
165
+ session.closed = true
166
+ if (session.isoDep == null) {
167
+ nativeComplete(session.token, CANCELLED, null, null)
168
+ }
169
+ if (session.txToken >= 0) {
170
+ nativeComplete(session.txToken, CANCELLED, null, null)
171
+ }
172
+ try {
173
+ session.isoDep?.close()
174
+ } catch (_: IOException) {
175
+ // The session is over either way.
176
+ }
177
+ main.post {
178
+ val activity = session.activity
179
+ if (!activity.isFinishing && !activity.isDestroyed) {
180
+ session.adapter.disableReaderMode(activity)
181
+ }
182
+ val sheet = session.sheet
183
+ if (sheet == null) {
184
+ return@post
185
+ }
186
+ if (text.isEmpty()) {
187
+ dismissSheet(session)
188
+ } else {
189
+ sheet.showEnd(text)
190
+ main.postDelayed({ dismissSheet(session) }, END_TEXT_DELAY_MS)
191
+ }
192
+ }
193
+ }
194
+ }
195
+
196
+ private fun onTag(session: Session, tag: Tag) {
197
+ if (this.session !== session || session.isoDep != null) return
198
+ val isoDep = IsoDep.get(tag) ?: return // not ISO-DEP: keep polling
199
+ try {
200
+ isoDep.connect()
201
+ isoDep.timeout = ISO_DEP_TIMEOUT_MS
202
+ } catch (e: IOException) {
203
+ return endSession(session, TAG_LOST, detailOf(e))
204
+ } catch (e: SecurityException) {
205
+ return endSession(session, TAG_LOST, detailOf(e))
206
+ }
207
+ session.isoDep = isoDep
208
+ nativeComplete(session.token, OK, null, null)
209
+ }
210
+
211
+ // Every failure ends the session, silently: pending calls get the status,
212
+ // the sheet goes away, and the next transmit answers from `ended`.
213
+ private fun endSession(session: Session, status: Int, detail: String?) {
214
+ if (this.session !== session) return
215
+ this.session = null
216
+ session.closed = true
217
+ endedStatus = status
218
+ endedDetail = detail
219
+ if (session.isoDep == null) {
220
+ nativeComplete(session.token, status, null, detail)
221
+ }
222
+ if (session.txToken >= 0) {
223
+ nativeComplete(session.txToken, status, null, detail)
224
+ }
225
+ try {
226
+ session.isoDep?.close()
227
+ } catch (_: IOException) {
228
+ // The session is over either way.
229
+ }
230
+ main.post {
231
+ val activity = session.activity
232
+ if (!activity.isFinishing && !activity.isDestroyed) {
233
+ session.adapter.disableReaderMode(activity)
234
+ }
235
+ dismissSheet(session)
236
+ }
237
+ }
238
+
239
+ // The sheet's window may already be gone when a late close or session
240
+ // end reaches the main thread.
241
+ private fun dismissSheet(session: Session) {
242
+ val sheet = session.sheet ?: return
243
+ val activity = session.activity
244
+ if (sheet.isShowing && !activity.isFinishing && !activity.isDestroyed) {
245
+ sheet.dismiss()
246
+ }
247
+ }
248
+
249
+ // The exception's simple class name only — never its message.
250
+ private fun detailOf(e: Exception): String = "android:" + e.javaClass.simpleName
251
+
252
+ @JvmStatic
253
+ private external fun nativeComplete(
254
+ token: Long,
255
+ status: Int,
256
+ response: ByteArray?,
257
+ detail: String?,
258
+ )
259
+ }
260
+
261
+ /**
262
+ * The trusted reader dialog: the kernel's prompt text (scrollable, never
263
+ * truncated) and a Cancel button. Touch filtering rejects clicks an overlay
264
+ * could have produced (A9), `setHideOverlayWindows` keeps overlays off the
265
+ * window (A8), and focus changes drive reader mode — polling only runs while
266
+ * this window has focus.
267
+ */
268
+ private class CardSheet(activity: Activity) : Dialog(activity) {
269
+ var onCancel: (() -> Unit)? = null
270
+ var onFocusChange: ((Boolean) -> Unit)? = null
271
+
272
+ private val text = TextView(activity).apply {
273
+ movementMethod = ScrollingMovementMethod()
274
+ maxLines = 10
275
+ }
276
+ private val cancel = Button(activity).apply {
277
+ setText(android.R.string.cancel)
278
+ filterTouchesWhenObscured = true
279
+ setOnClickListener { cancel() }
280
+ }
281
+ private val content = object : LinearLayout(activity) {
282
+ init {
283
+ orientation = VERTICAL
284
+ val pad = (20 * resources.displayMetrics.density).toInt()
285
+ setPadding(pad, pad, pad, pad)
286
+ }
287
+
288
+ override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
289
+ super.onWindowFocusChanged(hasWindowFocus)
290
+ onFocusChange?.invoke(hasWindowFocus)
291
+ }
292
+ }
293
+
294
+ init {
295
+ setCanceledOnTouchOutside(false)
296
+ setOnCancelListener { onCancel?.invoke() }
297
+ content.addView(
298
+ text,
299
+ LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f),
300
+ )
301
+ content.addView(cancel)
302
+ setContentView(content)
303
+ if (Build.VERSION.SDK_INT >= 31) {
304
+ window?.setHideOverlayWindows(true)
305
+ }
306
+ }
307
+
308
+ fun showPrompt(prompt: String) {
309
+ text.text = prompt
310
+ }
311
+
312
+ fun showEnd(text: String) {
313
+ this.text.text = text
314
+ cancel.visibility = View.GONE
315
+ }
316
+ }
@@ -0,0 +1,142 @@
1
+ package com.margelo.nitro.qntxwallet
2
+
3
+ import android.app.Activity
4
+ import android.util.Log
5
+ import androidx.activity.result.ActivityResult
6
+ import androidx.activity.result.ActivityResultLauncher
7
+ import androidx.activity.result.IntentSenderRequest
8
+ import androidx.activity.result.contract.ActivityResultContracts
9
+ import androidx.annotation.Keep
10
+ import androidx.fragment.app.FragmentActivity
11
+ import com.facebook.proguard.annotations.DoNotStrip
12
+ import com.google.android.gms.auth.api.identity.AuthorizationRequest
13
+ import com.google.android.gms.auth.api.identity.AuthorizationResult
14
+ import com.google.android.gms.auth.api.identity.ClearTokenRequest
15
+ import com.google.android.gms.auth.api.identity.Identity
16
+ import com.google.android.gms.common.api.ApiException
17
+ import com.google.android.gms.common.api.CommonStatusCodes
18
+ import com.google.android.gms.common.api.Scope
19
+ import com.google.android.gms.tasks.Task
20
+ import com.margelo.nitro.NitroModules
21
+ import com.margelo.nitro.core.Promise
22
+ import java.util.UUID
23
+ import kotlin.coroutines.resume
24
+ import kotlin.coroutines.resumeWithException
25
+ import kotlin.coroutines.suspendCoroutine
26
+
27
+ /**
28
+ * Google sign-in for `drive.appdata` access tokens (cloud backup): `accessToken(false)` is the
29
+ * silent path — it rejects `auth-required` when Google needs a consent screen; `accessToken(true)`
30
+ * launches that screen on the foreground activity. The token never enters a log: only exception
31
+ * types and status codes are logged.
32
+ */
33
+ @DoNotStrip
34
+ @Keep
35
+ class HybridGoogleDriveAuth : HybridGoogleDriveAuthSpec() {
36
+ private val scope = Scope("https://www.googleapis.com/auth/drive.appdata")
37
+
38
+ override fun accessToken(interactive: Boolean): Promise<String> = Promise.async {
39
+ val context = NitroModules.applicationContext
40
+ ?: throw cloudError("unavailable", "no-context")
41
+ val request =
42
+ AuthorizationRequest.builder().setRequestedScopes(listOf(scope)).build()
43
+ val result = try {
44
+ awaitTask(Identity.getAuthorizationClient(context).authorize(request))
45
+ } catch (e: ApiException) {
46
+ throw mapApiException(e)
47
+ }
48
+ val token = result.accessToken
49
+ if (token != null) {
50
+ return@async token
51
+ }
52
+ if (!result.hasResolution()) {
53
+ throw cloudError("failed", "not-configured")
54
+ }
55
+ if (!interactive) {
56
+ throw cloudError("auth-required", "needs-consent")
57
+ }
58
+ interactiveToken(result)
59
+ }
60
+
61
+ override fun clearToken(token: String): Promise<Unit> = Promise.async {
62
+ val context = NitroModules.applicationContext
63
+ ?: throw cloudError("unavailable", "no-context")
64
+ try {
65
+ awaitTask(
66
+ Identity.getAuthorizationClient(context)
67
+ .clearToken(ClearTokenRequest.builder().setToken(token).build())
68
+ )
69
+ Unit
70
+ } catch (e: ApiException) {
71
+ throw mapApiException(e)
72
+ }
73
+ }
74
+
75
+ /** Launches the consent PendingIntent on the foreground activity and resolves the new token. */
76
+ private suspend fun interactiveToken(result: AuthorizationResult): String {
77
+ val activity = foregroundActivity() ?: throw cloudError("unavailable", "no-activity")
78
+ val sender = result.pendingIntent?.intentSender
79
+ ?: throw cloudError("failed", "not-configured")
80
+ val granted: ActivityResult = suspendCoroutine { cont ->
81
+ val key = "qntx-drive-auth-${UUID.randomUUID()}"
82
+ // Registry access belongs on the main thread, so register and launch together there.
83
+ activity.runOnUiThread {
84
+ var launcher: ActivityResultLauncher<IntentSenderRequest>? = null
85
+ try {
86
+ launcher =
87
+ activity.activityResultRegistry.register(
88
+ key, ActivityResultContracts.StartIntentSenderForResult()
89
+ ) { outcome ->
90
+ launcher?.unregister()
91
+ cont.resume(outcome)
92
+ }
93
+ launcher.launch(IntentSenderRequest.Builder(sender).build())
94
+ } catch (e: Exception) {
95
+ launcher?.unregister()
96
+ cont.resumeWithException(cloudError("unavailable", "no-activity"))
97
+ }
98
+ }
99
+ }
100
+ if (granted.resultCode != Activity.RESULT_OK || granted.data == null) {
101
+ throw cloudError("auth-required", "cancelled")
102
+ }
103
+ val authorized = try {
104
+ Identity.getAuthorizationClient(activity).getAuthorizationResultFromIntent(granted.data)
105
+ } catch (e: ApiException) {
106
+ throw mapApiException(e)
107
+ }
108
+ return authorized.accessToken ?: throw cloudError("failed", "no-token")
109
+ }
110
+
111
+ private fun foregroundActivity(): FragmentActivity? =
112
+ NitroModules.applicationContext?.currentActivity as? FragmentActivity
113
+
114
+ private fun mapApiException(e: ApiException): Exception {
115
+ // Only the status code maps — the message can name the signed-in account.
116
+ Log.w(TAG, "api failure: ${e.statusCode}")
117
+ return when (e.statusCode) {
118
+ CommonStatusCodes.NETWORK_ERROR -> cloudError("unavailable", "network")
119
+ CommonStatusCodes.DEVELOPER_ERROR -> cloudError("failed", "not-configured")
120
+ CommonStatusCodes.SIGN_IN_REQUIRED, CommonStatusCodes.RESOLUTION_REQUIRED ->
121
+ cloudError("auth-required", "needs-consent")
122
+ else -> cloudError("failed", "api-${e.statusCode}")
123
+ }
124
+ }
125
+
126
+ private fun cloudError(code: String, detail: String): Exception =
127
+ Exception("[qntx-cloud:$code] $detail")
128
+
129
+ private suspend fun <T> awaitTask(task: Task<T>): T = suspendCoroutine { cont ->
130
+ task.addOnCompleteListener { done ->
131
+ if (done.isSuccessful) {
132
+ cont.resume(done.result)
133
+ } else {
134
+ cont.resumeWithException(done.exception ?: Exception("task failed"))
135
+ }
136
+ }
137
+ }
138
+
139
+ private companion object {
140
+ private const val TAG = "QntxDriveAuth"
141
+ }
142
+ }
@@ -0,0 +1,25 @@
1
+ package com.margelo.nitro.qntxwallet
2
+
3
+ import android.view.View
4
+ import androidx.annotation.Keep
5
+ import com.facebook.proguard.annotations.DoNotStrip
6
+ import com.facebook.react.uimanager.ThemedReactContext
7
+
8
+ /**
9
+ * The Nitro view behind `SecureInput`: it owns a SecureInputField and forwards
10
+ * its state transitions to the JS prop. Nothing else about the entry —
11
+ * characters, length, kind or label — crosses to the main runtime.
12
+ */
13
+ @DoNotStrip
14
+ @Keep
15
+ class HybridSecureInputView(context: ThemedReactContext) : HybridSecureInputViewSpec() {
16
+ private val field = SecureInputField(context)
17
+
18
+ override var onStateChange: (state: SecureInputState) -> Unit = {}
19
+
20
+ override val view: View = field
21
+
22
+ init {
23
+ field.onStateChange = { state -> onStateChange(state) }
24
+ }
25
+ }
@@ -3,6 +3,7 @@ package com.margelo.nitro.qntxwallet
3
3
  import android.app.KeyguardManager
4
4
  import android.content.Context
5
5
  import android.content.pm.PackageManager
6
+ import android.os.Build
6
7
  import android.os.LocaleList
7
8
  import android.security.keystore.KeyGenParameterSpec
8
9
  import android.security.keystore.KeyPermanentlyInvalidatedException
@@ -21,6 +22,7 @@ import com.facebook.proguard.annotations.DoNotStrip
21
22
  import com.margelo.nitro.NitroModules
22
23
  import java.security.KeyStore
23
24
  import java.util.concurrent.Executor
25
+ import java.util.concurrent.Executors
24
26
  import java.security.UnrecoverableKeyException
25
27
  import javax.crypto.Cipher
26
28
  import javax.crypto.KeyGenerator
@@ -29,11 +31,14 @@ import javax.crypto.spec.GCMParameterSpec
29
31
 
30
32
  /**
31
33
  * Android keystore (W5): one AndroidKeyStore AES-256-GCM key per vault factor
32
- * (`qntx-wallet.vault.<factor id>`), StrongBox-backed when present. Every use
33
- * needs a fresh BiometricPrompt (strong biometric or device credential) bound
34
- * to the cipher through a CryptoObject; the key survives biometric enrollment
35
- * changes and dies with the lock screen. The C++ host calls these entry points
36
- * with a completion token and receives the result through [nativeComplete].
34
+ * (`qntx-wallet.vault.<factor id>`), StrongBox-backed when present. A presence
35
+ * key needs a fresh BiometricPrompt (strong biometric or device credential)
36
+ * bound to the cipher through a CryptoObject on every use, survives biometric
37
+ * enrollment changes and dies with the lock screen. A device key requires no
38
+ * authentication, is used by the silent unlock factor and its crypto runs on a
39
+ * dedicated single-thread executor — never through BiometricPrompt and never
40
+ * on the main thread. The C++ host calls these entry points with a completion
41
+ * token and receives the result through [nativeComplete].
37
42
  * Sealed bytes are `iv(12) ‖ ciphertext ‖ tag(16)`.
38
43
  */
39
44
  @DoNotStrip
@@ -51,10 +56,14 @@ object Keystore {
51
56
  private const val INVALIDATED = 2
52
57
  private const val UNAVAILABLE = 3
53
58
  private const val FAILED = 4
54
- private const val NO_DEVICE_CREDENTIAL = 5
59
+ private const val NO_LOCK_SCREEN = 5
55
60
 
56
61
  @Volatile private var current: BiometricPrompt? = null
57
62
 
63
+ // All device-key work — key generation, GCM seal/open, probes, removes —
64
+ // serialized off the main thread; presence work never touches it.
65
+ private val deviceExecutor: Executor = Executors.newSingleThreadExecutor()
66
+
58
67
  @JvmStatic
59
68
  fun locale(): String = LocaleList.getDefault()[0]?.toLanguageTag() ?: "en"
60
69
 
@@ -67,7 +76,7 @@ object Keystore {
67
76
  }
68
77
  if (!deviceSecure(activity)) {
69
78
  secret.fill(0)
70
- return nativeComplete(token, NO_DEVICE_CREDENTIAL, null, null)
79
+ return nativeComplete(token, NO_LOCK_SCREEN, null, null)
71
80
  }
72
81
  val alias = PREFIX + id
73
82
  val cipher = try {
@@ -137,6 +146,106 @@ object Keystore {
137
146
  }
138
147
  }
139
148
 
149
+ @JvmStatic
150
+ fun sealDevice(token: Long, id: String, secret: ByteArray) {
151
+ deviceExecutor.execute {
152
+ try {
153
+ val context = NitroModules.applicationContext
154
+ val alias = PREFIX + id
155
+ keyStore().deleteEntry(alias)
156
+ val cipher = Cipher.getInstance(TRANSFORMATION).apply {
157
+ init(Cipher.ENCRYPT_MODE, generateDevice(alias, context))
158
+ }
159
+ nativeComplete(token, OK, cipher.iv + cipher.doFinal(secret), null)
160
+ } catch (e: Exception) {
161
+ nativeComplete(token, UNAVAILABLE, null, detailOf(e))
162
+ } finally {
163
+ secret.fill(0)
164
+ }
165
+ }
166
+ }
167
+
168
+ @JvmStatic
169
+ fun openDevice(token: Long, id: String, sealed: ByteArray) {
170
+ deviceExecutor.execute {
171
+ if (sealed.size <= IV_BYTES + TAG_BITS / 8) {
172
+ return@execute nativeComplete(token, FAILED, null, null)
173
+ }
174
+ val alias = PREFIX + id
175
+ val key = try {
176
+ keyStore().getKey(alias, null) as? SecretKey
177
+ } catch (e: UnrecoverableKeyException) {
178
+ null
179
+ } ?: return@execute nativeComplete(token, INVALIDATED, null, null)
180
+ val cipher = try {
181
+ Cipher.getInstance(TRANSFORMATION).apply {
182
+ init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, sealed, 0, IV_BYTES))
183
+ }
184
+ } catch (e: KeyPermanentlyInvalidatedException) {
185
+ return@execute nativeComplete(token, INVALIDATED, null, detailOf(e))
186
+ } catch (e: Exception) {
187
+ return@execute nativeComplete(token, FAILED, null, detailOf(e))
188
+ }
189
+ val plain = try {
190
+ cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES)
191
+ } catch (e: Exception) {
192
+ return@execute nativeComplete(token, FAILED, null, detailOf(e))
193
+ }
194
+ try {
195
+ nativeComplete(token, OK, plain, null)
196
+ } finally {
197
+ plain.fill(0)
198
+ }
199
+ }
200
+ }
201
+
202
+ @JvmStatic
203
+ fun probe(token: Long, id: String, presence: Boolean) {
204
+ deviceExecutor.execute {
205
+ val alias = PREFIX + id
206
+ val key = try {
207
+ keyStore().getKey(alias, null) as? SecretKey
208
+ } catch (e: UnrecoverableKeyException) {
209
+ null
210
+ } catch (e: Exception) {
211
+ return@execute nativeComplete(token, FAILED, null, detailOf(e))
212
+ }
213
+ if (key == null) {
214
+ return@execute nativeComplete(token, INVALIDATED, null, null)
215
+ }
216
+ try {
217
+ Cipher.getInstance(TRANSFORMATION).init(
218
+ Cipher.DECRYPT_MODE,
219
+ key,
220
+ GCMParameterSpec(TAG_BITS, ByteArray(IV_BYTES)),
221
+ )
222
+ } catch (e: KeyPermanentlyInvalidatedException) {
223
+ return@execute nativeComplete(token, INVALIDATED, null, detailOf(e))
224
+ } catch (e: Exception) {
225
+ return@execute nativeComplete(token, FAILED, null, detailOf(e))
226
+ }
227
+ // A per-use-authentication key cannot be alive while the device has no
228
+ // lock screen at all.
229
+ if (presence && NitroModules.applicationContext?.let(::deviceSecure) != true) {
230
+ return@execute nativeComplete(token, INVALIDATED, null, null)
231
+ }
232
+ nativeComplete(token, OK, null, null)
233
+ }
234
+ }
235
+
236
+ @JvmStatic
237
+ fun remove(token: Long, id: String) {
238
+ deviceExecutor.execute {
239
+ val status = try {
240
+ keyStore().deleteEntry(PREFIX + id)
241
+ OK
242
+ } catch (e: Exception) {
243
+ FAILED
244
+ }
245
+ nativeComplete(token, status, null, null)
246
+ }
247
+ }
248
+
140
249
  @JvmStatic
141
250
  fun authenticate(token: Long, title: String, description: String) {
142
251
  val activity = foregroundActivity()
@@ -144,7 +253,7 @@ object Keystore {
144
253
  return nativeComplete(token, UNAVAILABLE, null, "android:no-activity")
145
254
  }
146
255
  if (!deviceSecure(activity)) {
147
- return nativeComplete(token, NO_DEVICE_CREDENTIAL, null, null)
256
+ return nativeComplete(token, NO_LOCK_SCREEN, null, null)
148
257
  }
149
258
  prompt(activity, title, description, null) { status, detail, _ ->
150
259
  nativeComplete(token, status, null, detail)
@@ -208,6 +317,36 @@ object Keystore {
208
317
  .generateKey()
209
318
  }
210
319
 
320
+ private fun generateDevice(alias: String, context: Context?): SecretKey {
321
+ val strongBox =
322
+ context?.packageManager?.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE) == true
323
+ return try {
324
+ generateDevice(alias, strongBox)
325
+ } catch (e: StrongBoxUnavailableException) {
326
+ generateDevice(alias, false)
327
+ }
328
+ }
329
+
330
+ private fun generateDevice(alias: String, strongBox: Boolean): SecretKey {
331
+ val spec = KeyGenParameterSpec.Builder(
332
+ alias,
333
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
334
+ )
335
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
336
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
337
+ .setKeySize(256)
338
+ .setIsStrongBoxBacked(strongBox)
339
+ .apply {
340
+ // Android 12–14 bug: such keys cannot be created or used without a
341
+ // secure lock screen and are deleted when it is removed (fixed in 15).
342
+ if (Build.VERSION.SDK_INT >= 35) setUnlockedDeviceRequired(true)
343
+ }
344
+ .build()
345
+ return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
346
+ .apply { init(spec) }
347
+ .generateKey()
348
+ }
349
+
211
350
  /** Shows one system verification on the main thread; [done] runs there with the outcome. */
212
351
  private fun prompt(
213
352
  activity: FragmentActivity,
@@ -280,7 +419,7 @@ object Keystore {
280
419
  BiometricPrompt.ERROR_NEGATIVE_BUTTON,
281
420
  BiometricPrompt.ERROR_CANCELED,
282
421
  BiometricPrompt.ERROR_TIMEOUT -> CANCELLED
283
- BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL -> NO_DEVICE_CREDENTIAL
422
+ BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL -> NO_LOCK_SCREEN
284
423
  BiometricPrompt.ERROR_HW_UNAVAILABLE,
285
424
  BiometricPrompt.ERROR_HW_NOT_PRESENT,
286
425
  BiometricPrompt.ERROR_NO_BIOMETRICS -> UNAVAILABLE