@qntx/wallet-native 0.13.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 +42170 -12741
  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,422 @@
1
+ package com.margelo.nitro.qntxwallet
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.app.Activity
5
+ import android.content.Context
6
+ import android.content.ContextWrapper
7
+ import android.graphics.Typeface
8
+ import android.os.Build
9
+ import android.text.Editable
10
+ import android.text.InputFilter
11
+ import android.text.InputType
12
+ import android.text.method.TransformationMethod
13
+ import android.view.ActionMode
14
+ import android.view.KeyEvent
15
+ import android.view.Menu
16
+ import android.view.MenuItem
17
+ import android.view.View
18
+ import android.view.WindowManager
19
+ import android.view.inputmethod.EditorInfo
20
+ import android.widget.EditText
21
+ import android.widget.LinearLayout
22
+ import android.widget.TextView
23
+ import androidx.annotation.Keep
24
+ import com.facebook.proguard.annotations.DoNotStrip
25
+
26
+ // SecureInputKind ordinals shared with cpp/host/SecureInput.hpp.
27
+ private const val KIND_ACCESS_CODE = 0
28
+ private const val KIND_SHORT_ID = 1
29
+ private const val KIND_BACKUP_PASSWORD = 2
30
+ private const val KIND_SESSION_APPROVAL = 3
31
+
32
+ /**
33
+ * The Android half of the trusted input surface: a label the kernel sets
34
+ * plus an EditText whose characters leave the process only as bytes through
35
+ * SecureInputHub — never through the main runtime, which sees only state
36
+ * transitions. The field is disabled until a request arms it.
37
+ */
38
+ @DoNotStrip
39
+ @Keep
40
+ @SuppressLint("AppCompatCustomView")
41
+ class SecureInputField(context: Context) : LinearLayout(context) {
42
+ var onStateChange: ((SecureInputState) -> Unit)? = null
43
+
44
+ private val label = TextView(context)
45
+ private val field = Field(context)
46
+
47
+ private var hubId = 0L
48
+ private var kind = KIND_ACCESS_CODE
49
+ private var justSubmitted = false
50
+ private var state = SecureInputState.IDLE
51
+ private var secureSet = false
52
+ private var hadSecureFlag = false
53
+ private var disarming = false
54
+
55
+ init {
56
+ orientation = VERTICAL
57
+ addView(label)
58
+ addView(field)
59
+ disarm()
60
+ }
61
+
62
+ override fun requestLayout() {
63
+ super.requestLayout()
64
+ // React Native owns this host view's frame and swallows child layout
65
+ // requests, so a label going GONE→VISIBLE would never be measured.
66
+ // Measure and lay out ourselves on the next main-loop pass.
67
+ post {
68
+ measure(
69
+ MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
70
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
71
+ )
72
+ layout(left, top, right, bottom)
73
+ }
74
+ }
75
+
76
+ override fun onAttachedToWindow() {
77
+ super.onAttachedToWindow()
78
+ if (hubId == 0L) {
79
+ hubId = nativeAttach()
80
+ }
81
+ }
82
+
83
+ override fun onDetachedFromWindow() {
84
+ super.onDetachedFromWindow()
85
+ if (hubId != 0L) {
86
+ nativeDetach(hubId)
87
+ hubId = 0L
88
+ }
89
+ disarm()
90
+ }
91
+
92
+ // Invoked by the C++ hub sink on the kernel's thread — hop to the main
93
+ // Looper before touching the views.
94
+ @Keep
95
+ fun deliver(kind: Int, labelText: String?) {
96
+ post { applyPrompt(kind, labelText) }
97
+ }
98
+
99
+ private fun applyPrompt(kind: Int, labelText: String?) {
100
+ if (labelText == null) {
101
+ val submitted = justSubmitted
102
+ justSubmitted = false
103
+ disarm(submitted)
104
+ return
105
+ }
106
+ justSubmitted = false
107
+ this.kind = kind
108
+ label.text = labelText
109
+ arm()
110
+ }
111
+
112
+ private fun arm() {
113
+ label.visibility = VISIBLE
114
+ field.isEnabled = true
115
+ field.inputType =
116
+ when (kind) {
117
+ KIND_SESSION_APPROVAL -> InputType.TYPE_CLASS_NUMBER
118
+ KIND_SHORT_ID ->
119
+ InputType.TYPE_CLASS_TEXT or
120
+ InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
121
+ InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
122
+ else -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
123
+ }
124
+ // Never reveal characters: PasswordTransformationMethod shows the last
125
+ // typed char when the system setting is on — mask every char ourselves.
126
+ // The readable kinds (short id, approval code) carry no secret: the label
127
+ // itself shows the approval code.
128
+ field.transformationMethod =
129
+ if (kind == KIND_SHORT_ID || kind == KIND_SESSION_APPROVAL) {
130
+ null
131
+ } else {
132
+ MaskTransformation
133
+ }
134
+ field.filters =
135
+ when (kind) {
136
+ KIND_ACCESS_CODE -> arrayOf(accessCodeFilter)
137
+ KIND_BACKUP_PASSWORD -> arrayOf(backupPasswordFilter)
138
+ KIND_SESSION_APPROVAL -> arrayOf(sessionApprovalFilter)
139
+ else -> arrayOf(shortIdFilter)
140
+ }
141
+ field.typeface =
142
+ if (kind == KIND_SHORT_ID || kind == KIND_SESSION_APPROVAL) {
143
+ Typeface.MONOSPACE
144
+ } else {
145
+ Typeface.DEFAULT
146
+ }
147
+ if (kind != KIND_SHORT_ID && kind != KIND_SESSION_APPROVAL && !secureSet) {
148
+ activityWindow()?.let { window ->
149
+ hadSecureFlag =
150
+ window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE != 0
151
+ // The entry is a secret; keep it off screenshots and untrusted
152
+ // displays while it is being typed (S6).
153
+ window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
154
+ secureSet = true
155
+ }
156
+ }
157
+ emit(SecureInputState.EMPTY)
158
+ // A mounted view that just armed takes the keyboard; the latest
159
+ // attach wins over fields armed earlier.
160
+ if (isAttachedToWindow) {
161
+ field.requestFocus()
162
+ showKeyboard()
163
+ }
164
+ }
165
+
166
+ private fun disarm(submitted: Boolean = false) {
167
+ // Editable content cannot be erased; overwrite it before clearing — the
168
+ // best the platform can do. The overwrite fires the watcher, so
169
+ // suppress it: the runtime sees (submitted then) idle, nothing else.
170
+ disarming = true
171
+ val text = field.text
172
+ if (text.isNotEmpty()) {
173
+ text.replace(0, text.length, "0".repeat(text.length))
174
+ }
175
+ text.clear()
176
+ disarming = false
177
+ field.isEnabled = false
178
+ field.clearFocus()
179
+ hideKeyboard()
180
+ if (secureSet) {
181
+ secureSet = false
182
+ activityWindow()?.let { window ->
183
+ if (hadSecureFlag) {
184
+ window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
185
+ } else {
186
+ window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
187
+ }
188
+ }
189
+ }
190
+ label.text = null
191
+ label.visibility = GONE
192
+ if (submitted) {
193
+ emit(SecureInputState.SUBMITTED)
194
+ }
195
+ emit(SecureInputState.IDLE)
196
+ }
197
+
198
+ private fun emit(next: SecureInputState) {
199
+ if (state == next) return
200
+ state = next
201
+ onStateChange?.invoke(next)
202
+ }
203
+
204
+ private fun onTextChanged() {
205
+ if (disarming) return
206
+ emit(
207
+ if (field.text.isEmpty()) SecureInputState.EMPTY else SecureInputState.FILLED,
208
+ )
209
+ }
210
+
211
+ private fun submit() {
212
+ val text = field.text
213
+ val ready =
214
+ when (kind) {
215
+ KIND_SHORT_ID -> text.length == 8
216
+ KIND_SESSION_APPROVAL -> text.length == 4
217
+ else -> text.isNotEmpty()
218
+ }
219
+ if (!ready) return
220
+ // The ASCII-only kinds are one char per byte; a backup password is
221
+ // arbitrary Unicode, handed over as real UTF-8.
222
+ val bytes =
223
+ if (kind == KIND_BACKUP_PASSWORD) {
224
+ text.toString().toByteArray(Charsets.UTF_8)
225
+ } else {
226
+ ByteArray(text.length) { i -> text[i].code.toByte() }
227
+ }
228
+ justSubmitted = nativeSubmit(hubId, bytes)
229
+ if (!justSubmitted) {
230
+ // The hub refused it; drop the local copy now too — its own clear
231
+ // arrives on this queue right behind.
232
+ text.clear()
233
+ emit(SecureInputState.EMPTY)
234
+ }
235
+ }
236
+
237
+ private fun activityWindow(): android.view.Window? {
238
+ var context = context
239
+ while (context is ContextWrapper) {
240
+ if (context is Activity) return context.window
241
+ context = context.baseContext
242
+ }
243
+ return null
244
+ }
245
+
246
+ private fun hideKeyboard() {
247
+ val imm =
248
+ context.getSystemService(Context.INPUT_METHOD_SERVICE)
249
+ as android.view.inputmethod.InputMethodManager
250
+ imm.hideSoftInputFromWindow(field.windowToken, 0)
251
+ }
252
+
253
+ private fun showKeyboard() {
254
+ val imm =
255
+ context.getSystemService(Context.INPUT_METHOD_SERVICE)
256
+ as android.view.inputmethod.InputMethodManager
257
+ imm.showSoftInput(field, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
258
+ }
259
+
260
+ @Keep
261
+ private external fun nativeAttach(): Long
262
+
263
+ @Keep
264
+ private external fun nativeDetach(id: Long)
265
+
266
+ @Keep
267
+ private external fun nativeSubmit(id: Long, bytes: ByteArray): Boolean
268
+
269
+ // The characters the transformation shows — dots only, one per char, so
270
+ // the secret's glyphs never exist as a displayable String either. Like
271
+ // PasswordCharSequence, it must delegate length to the live source: a
272
+ // frozen snapshot leaves the Layout measuring offsets against a stale
273
+ // length and the cursor-anchor notifier crashes ("Invalid Context
274
+ // Range").
275
+ private class Masked(private val source: CharSequence) : CharSequence {
276
+ override val length: Int
277
+ get() = source.length
278
+
279
+ override fun get(index: Int): Char = '•'
280
+
281
+ override fun subSequence(startIndex: Int, endIndex: Int): CharSequence =
282
+ Masked(source.subSequence(startIndex, endIndex))
283
+ }
284
+
285
+ private object MaskTransformation : TransformationMethod {
286
+ override fun getTransformation(source: CharSequence, view: View): CharSequence =
287
+ Masked(source)
288
+
289
+ override fun onFocusChanged(
290
+ view: View,
291
+ sourceText: CharSequence,
292
+ focused: Boolean,
293
+ direction: Int,
294
+ previouslyFocusedRect: android.graphics.Rect?,
295
+ ) {}
296
+ }
297
+
298
+ // An EditText that never offers the selection or insertion menus: the
299
+ // main runtime can read the clipboard, so copy/paste is cut off in both
300
+ // directions, and autofill and accessibility services get nothing (S8/S9).
301
+ @SuppressLint("AppCompatCustomView")
302
+ private inner class Field(context: Context) : EditText(context) {
303
+ init {
304
+ importantForAutofill = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
305
+ if (Build.VERSION.SDK_INT >= 34) {
306
+ setAccessibilityDataSensitive(ACCESSIBILITY_DATA_SENSITIVE_YES)
307
+ }
308
+ isLongClickable = false
309
+ imeOptions =
310
+ EditorInfo.IME_ACTION_DONE or
311
+ EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING or
312
+ EditorInfo.IME_FLAG_NO_EXTRACT_UI
313
+ val noMenu =
314
+ object : ActionMode.Callback {
315
+ override fun onCreateActionMode(mode: ActionMode, menu: Menu) = false
316
+ override fun onPrepareActionMode(mode: ActionMode, menu: Menu) = false
317
+ override fun onActionItemClicked(mode: ActionMode, item: MenuItem) = false
318
+ override fun onDestroyActionMode(mode: ActionMode) {}
319
+ }
320
+ customSelectionActionModeCallback = noMenu
321
+ customInsertionActionModeCallback = noMenu
322
+ setOnEditorActionListener { _, actionId, event ->
323
+ val done =
324
+ actionId == EditorInfo.IME_ACTION_DONE ||
325
+ (event?.keyCode == KeyEvent.KEYCODE_ENTER &&
326
+ event.action == KeyEvent.ACTION_DOWN)
327
+ if (done) submit()
328
+ done
329
+ }
330
+ addTextChangedListener(
331
+ object : android.text.TextWatcher {
332
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
333
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {
334
+ this@SecureInputField.onTextChanged()
335
+ }
336
+ override fun afterTextChanged(s: Editable?) {}
337
+ },
338
+ )
339
+ }
340
+ }
341
+
342
+ private companion object {
343
+ // Returns the text the range keeps when an edit is refused: returning
344
+ // the replaced span itself cancels the change without deleting it.
345
+ private fun refuse(dest: CharSequence, dstart: Int, dend: Int): CharSequence =
346
+ dest.subSequence(dstart, dend)
347
+
348
+ val accessCodeFilter =
349
+ InputFilter { source, start, end, dest, dstart, dend ->
350
+ val next = dest.length - (dend - dstart) + (end - start)
351
+ var allowed = next <= 64
352
+ if (allowed) {
353
+ for (i in start until end) {
354
+ val c = source[i]
355
+ if (c < ' ' || c > '~') {
356
+ allowed = false
357
+ break
358
+ }
359
+ }
360
+ }
361
+ if (allowed) null else refuse(dest, dstart, dend)
362
+ }
363
+
364
+ // Any characters, bounded by 1024 UTF-8 bytes — the wire's own limit;
365
+ // the hub rechecks validity on submit.
366
+ val backupPasswordFilter =
367
+ InputFilter { source, start, end, dest, dstart, dend ->
368
+ val next =
369
+ StringBuilder(dest).replace(
370
+ dstart,
371
+ dend,
372
+ source.subSequence(start, end).toString(),
373
+ )
374
+ if (next.toString().toByteArray(Charsets.UTF_8).size <= 1024) {
375
+ null
376
+ } else {
377
+ refuse(dest, dstart, dend)
378
+ }
379
+ }
380
+
381
+ // Decimal digits only, four at most.
382
+ val sessionApprovalFilter =
383
+ InputFilter { source, start, end, dest, dstart, dend ->
384
+ val next = dest.length - (dend - dstart) + (end - start)
385
+ var allowed = next <= 4
386
+ if (allowed) {
387
+ for (i in start until end) {
388
+ if (source[i] !in '0'..'9') {
389
+ allowed = false
390
+ break
391
+ }
392
+ }
393
+ }
394
+ if (allowed) null else refuse(dest, dstart, dend)
395
+ }
396
+
397
+ val shortIdFilter =
398
+ InputFilter { source, start, end, dest, dstart, dend ->
399
+ val filtered = StringBuilder()
400
+ var kept = dest.length - (dend - dstart)
401
+ var allowed = true
402
+ for (i in start until end) {
403
+ var c = source[i]
404
+ if (c == '-') continue
405
+ if (c in 'a'..'f') c = c.uppercaseChar()
406
+ if (!(c in '0'..'9' || c in 'A'..'F') || kept >= 8) {
407
+ allowed = false
408
+ break
409
+ }
410
+ filtered.append(c)
411
+ kept++
412
+ }
413
+ if (!allowed) {
414
+ refuse(dest, dstart, dend)
415
+ } else if (filtered.toString() == source.subSequence(start, end).toString()) {
416
+ null
417
+ } else {
418
+ filtered.toString()
419
+ }
420
+ }
421
+ }
422
+ }
@@ -0,0 +1,90 @@
1
+ package com.margelo.nitro.qntxwallet
2
+
3
+ import android.security.keystore.KeyGenParameterSpec
4
+ import android.security.keystore.KeyProperties
5
+ import androidx.annotation.Keep
6
+ import com.facebook.proguard.annotations.DoNotStrip
7
+ import java.security.KeyStore
8
+ import javax.crypto.KeyGenerator
9
+
10
+ /**
11
+ * Android vault anchor: the record lives in Android Keystore entry *aliases*
12
+ * `qntx-wallet.anchor.<seq as 16 lowercase hex>.<record as lowercase hex>` —
13
+ * the platform gives an app no keystore byte store or monotonic counter of its
14
+ * own (rollback resistance inside key blobs is platform-only and @hide), and
15
+ * keystore2's database sits outside the app's data directory and is not
16
+ * backed up. `store` writes under the next
17
+ * sequence alias, then deletes every other anchor alias: a crash between the
18
+ * two leaves both, and the higher sequence wins. The key material is never
19
+ * used — only the alias carries data — so entries are plain AES-128 keys with
20
+ * no user authentication and no StrongBox. The prefix differs from the factor
21
+ * keys' `qntx-wallet.vault.` so `Keystore.clear()` never deletes the anchor.
22
+ */
23
+ @DoNotStrip
24
+ @Keep
25
+ object VaultAnchor {
26
+ private const val PREFIX = "qntx-wallet.anchor."
27
+ private const val PROVIDER = "AndroidKeyStore"
28
+ private val ALIAS =
29
+ Regex("^${Regex.escape(PREFIX)}([0-9a-f]{16})\\.((?:[0-9a-f]{2})+)$")
30
+
31
+ private fun keyStore(): KeyStore =
32
+ KeyStore.getInstance(PROVIDER).apply { load(null) }
33
+
34
+ /** Highest sequence + record of every well-formed anchor alias; malformed
35
+ * aliases with the prefix are corruption, not a miss. */
36
+ private fun highest(store: KeyStore): Pair<ULong, ByteArray>? {
37
+ var best: Pair<ULong, ByteArray>? = null
38
+ for (alias in store.aliases().toList()) {
39
+ if (!alias.startsWith(PREFIX)) {
40
+ continue
41
+ }
42
+ val match = ALIAS.matchEntire(alias)
43
+ ?: throw IllegalStateException("malformed vault anchor alias")
44
+ val seq = match.groupValues[1].toULong(16)
45
+ if (best == null || seq > best.first) {
46
+ best = seq to match.groupValues[2].chunked(2)
47
+ .map { it.toInt(16).toByte() }
48
+ .toByteArray()
49
+ }
50
+ }
51
+ return best
52
+ }
53
+
54
+ /** The current anchor record, or null when nothing is stored. */
55
+ @JvmStatic
56
+ @DoNotStrip
57
+ @Keep
58
+ fun load(): ByteArray? = highest(keyStore())?.second
59
+
60
+ /**
61
+ * Store `bytes` under the next sequence alias, then delete every other
62
+ * anchor alias. Callers serialize under the C++ CAS mutex, so the
63
+ * scan-then-write here cannot race itself.
64
+ */
65
+ @JvmStatic
66
+ @DoNotStrip
67
+ @Keep
68
+ fun store(bytes: ByteArray) {
69
+ val store = keyStore()
70
+ val seq = when (val top = highest(store)?.first) {
71
+ null -> 0uL
72
+ ULong.MAX_VALUE ->
73
+ throw IllegalStateException("vault anchor sequence exhausted")
74
+ else -> top + 1uL
75
+ }
76
+ val alias = PREFIX + seq.toString(16).padStart(16, '0') + "." +
77
+ bytes.joinToString("") { "%02x".format(it) }
78
+ val spec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT)
79
+ .setKeySize(128)
80
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
81
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
82
+ .build()
83
+ KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
84
+ .apply { init(spec) }
85
+ .generateKey()
86
+ store.aliases().toList()
87
+ .filter { it.startsWith(PREFIX) && it != alias }
88
+ .forEach(store::deleteEntry)
89
+ }
90
+ }
@@ -5,9 +5,14 @@ import androidx.annotation.Nullable;
5
5
  import com.facebook.react.bridge.NativeModule;
6
6
  import com.facebook.react.bridge.ReactApplicationContext;
7
7
  import com.facebook.react.module.model.ReactModuleInfoProvider;
8
+ import com.facebook.react.uimanager.ViewManager;
8
9
  import com.facebook.react.BaseReactPackage;
9
10
 
11
+ import com.margelo.nitro.qntxwallet.views.HybridSecureInputViewManager;
12
+
13
+ import java.util.Arrays;
10
14
  import java.util.HashMap;
15
+ import java.util.List;
11
16
 
12
17
  public class WalletNativePackage extends BaseReactPackage {
13
18
  @Nullable
@@ -16,6 +21,11 @@ public class WalletNativePackage extends BaseReactPackage {
16
21
  return null;
17
22
  }
18
23
 
24
+ @Override
25
+ public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
26
+ return Arrays.asList(new HybridSecureInputViewManager());
27
+ }
28
+
19
29
  @Override
20
30
  public ReactModuleInfoProvider getReactModuleInfoProvider() {
21
31
  return () -> {
@@ -0,0 +1,70 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <functional>
5
+ #include <memory>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ namespace qntx {
10
+
11
+ // The platform NFC reader behind `__qntx.cardReader`: an object the host
12
+ // packages provide so APDU bytes and the session's visible text flow only
13
+ // between the kernel and native code — never through the main runtime. The
14
+ // kernel builds the trusted summary and hands it to open() verbatim; the
15
+ // platform displays it while it polls for an ISO-DEP tag and must never
16
+ // truncate or replace it. iOS: NFCTagReaderSession; Android: reader mode with
17
+ // the module's own dialog. platformCardReader() has exactly one strong
18
+ // definition per platform; host tests link a fake.
19
+
20
+ // How a reader call ended. The binding maps each status to the kernel's
21
+ // failure code: cancelled → "cancelled", timeout → "timeout",
22
+ // tagLost → "tag-lost", interrupted → "interrupted",
23
+ // unavailable → "unavailable". The values are part of the Android JNI
24
+ // contract.
25
+ enum class CardReaderStatus {
26
+ ok = 0,
27
+ cancelled = 1,
28
+ timeout = 2,
29
+ tagLost = 3,
30
+ interrupted = 4,
31
+ unavailable = 5,
32
+ };
33
+
34
+ struct CardReaderResult {
35
+ CardReaderStatus status = CardReaderStatus::unavailable;
36
+ // transmit: the card's response data with SW1SW2 appended, 2..258 bytes.
37
+ std::vector<uint8_t> response;
38
+ // A "<domain>:<code>" diagnostic (e.g. "NFCError:202"), empty when none.
39
+ std::string detail;
40
+ };
41
+
42
+ // Completion callbacks run exactly once, on any thread.
43
+ using CardReaderDone = std::function<void(CardReaderResult)>;
44
+
45
+ // Platform contract:
46
+ // - open() shows `prompt` and completes ok once an ISO-DEP card is connected;
47
+ // until then a non-ISO-DEP tag or multiple tags are re-polled without
48
+ // changing the text.
49
+ // - After a successful open, a session-ending event (user cancel, system
50
+ // timeout, loss of focus) fails the in-flight transmit — or the next one
51
+ // when none is in flight — with that event's status. After any failure the
52
+ // session is over: it is never polled again.
53
+ // - close() ends the session and is idempotent; failure with an empty text is
54
+ // a silent close, otherwise `text` is the result message shown to the user.
55
+ class CardReader {
56
+ public:
57
+ virtual ~CardReader() = default;
58
+
59
+ virtual void open(std::string prompt, CardReaderDone done) = 0;
60
+
61
+ // Only after a successful open; an ok result carries data ‖ SW1 ‖ SW2.
62
+ virtual void transmit(std::vector<uint8_t> apdu, CardReaderDone done) = 0;
63
+
64
+ virtual void close(bool success, std::string text) = 0;
65
+ };
66
+
67
+ // The platform's reader; every KernelRuntime shares it.
68
+ std::shared_ptr<CardReader> platformCardReader();
69
+
70
+ } // namespace qntx