@blotch/angular-lynx-native 22.3.0 → 22.3.2

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 (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +143 -2
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +37 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +70 -1
  35. package/templates/android/app/src/main/AndroidManifest.xml +24 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,433 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.KeyguardManager
4
+ import android.content.Context
5
+ import android.content.SharedPreferences
6
+ import android.content.pm.PackageManager
7
+ import android.os.Build
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.security.keystore.KeyGenParameterSpec
11
+ import android.security.keystore.KeyPermanentlyInvalidatedException
12
+ import android.security.keystore.KeyProperties
13
+ import android.util.Base64
14
+ import androidx.biometric.BiometricManager
15
+ import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
16
+ import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK
17
+ import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
18
+ import androidx.biometric.BiometricPrompt
19
+ import androidx.core.content.ContextCompat
20
+ import androidx.fragment.app.FragmentActivity
21
+ import com.lynx.jsbridge.LynxMethod
22
+ import com.lynx.jsbridge.LynxModule
23
+ import com.lynx.react.bridge.Callback
24
+ import com.lynx.react.bridge.JavaOnlyMap
25
+ import com.lynx.react.bridge.ReadableMap
26
+ import java.security.KeyFactory
27
+ import java.security.KeyPairGenerator
28
+ import java.security.KeyStore
29
+ import java.security.PrivateKey
30
+ import java.security.PublicKey
31
+ import java.security.spec.MGF1ParameterSpec
32
+ import java.security.spec.X509EncodedKeySpec
33
+ import java.util.concurrent.Executors
34
+ import javax.crypto.Cipher
35
+ import javax.crypto.KeyGenerator
36
+ import javax.crypto.spec.GCMParameterSpec
37
+ import javax.crypto.spec.OAEPParameterSpec
38
+ import javax.crypto.spec.PSource
39
+ import javax.crypto.spec.SecretKeySpec
40
+
41
+ /**
42
+ * The native module behind the runtime's `LynxBiometrics`, and the values
43
+ * `LynxSecureStorage` keeps behind a fingerprint or a face
44
+ * (`requireBiometrics`). The runtime calls it as
45
+ * `NativeModules.AngularLynxBiometrics`, from the background thread, where
46
+ * NativeModules lives. MainActivity registers it with itself as the param:
47
+ * AndroidX's BiometricPrompt shows over a FragmentActivity.
48
+ *
49
+ * Only an app with `permissions.biometrics` in angular.json has this file,
50
+ * AndroidX Biometric, and MainActivity's lines that register it: the
51
+ * generator takes them out of the others.
52
+ *
53
+ * It counts only strong (Class 3) biometrics, the ones that can unlock a
54
+ * Keystore key, so `authenticate()` and the guarded values agree on what
55
+ * confirms the person.
56
+ *
57
+ * A guarded value is sealed with AES-GCM under a key of its own, and that key
58
+ * with RSA-OAEP under a Keystore key pair whose private key needs a
59
+ * biometric for each use. The public key needs none, so storing a value
60
+ * doesn't prompt, and reading one does, through BiometricPrompt's
61
+ * CryptoObject. Enrolling a new fingerprint or face invalidates the pair,
62
+ * and with it every guarded value, which then reads as none, as on iOS.
63
+ *
64
+ * Each method calls back once with `{}`, `{ value }`, the availability, or
65
+ * `{ error, message }`, where `error` is one of the runtime's
66
+ * BiometricsErrorCode values.
67
+ */
68
+ class BiometricsModule(context: Context, param: Any?) : LynxModule(context, param) {
69
+ private val activity = param as FragmentActivity
70
+ private val main = Handler(Looper.getMainLooper())
71
+ private val preferences: SharedPreferences =
72
+ activity.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
73
+
74
+ // Whether a prompt is open: BiometricPrompt shows one at a time. Read
75
+ // and written on the main thread only.
76
+ private var prompting = false
77
+
78
+ /** `{ type, enrolled, deviceCredential }`. */
79
+ @LynxMethod
80
+ fun availability(callback: Callback) {
81
+ val status = BiometricManager.from(activity).canAuthenticate(BIOMETRIC_STRONG)
82
+ val packages = activity.packageManager
83
+ val type =
84
+ when {
85
+ status == BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> "none"
86
+ packages.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT) -> "fingerprint"
87
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
88
+ packages.hasSystemFeature(PackageManager.FEATURE_FACE) -> "face"
89
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
90
+ packages.hasSystemFeature(PackageManager.FEATURE_IRIS) -> "iris"
91
+ status == BiometricManager.BIOMETRIC_SUCCESS ||
92
+ status == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> "fingerprint"
93
+ else -> "none"
94
+ }
95
+ val keyguard = activity.getSystemService(KeyguardManager::class.java)
96
+ callback.invoke(
97
+ JavaOnlyMap.from(
98
+ mapOf(
99
+ "type" to type,
100
+ "enrolled" to (status == BiometricManager.BIOMETRIC_SUCCESS),
101
+ "deviceCredential" to (keyguard?.isDeviceSecure == true),
102
+ ),
103
+ ),
104
+ )
105
+ }
106
+
107
+ /**
108
+ * Shows the prompt with `{ reason, allowDeviceCredential, title,
109
+ * cancelLabel }`, and calls back with `{}` once the person is confirmed.
110
+ */
111
+ @LynxMethod
112
+ fun authenticate(options: ReadableMap, callback: Callback) {
113
+ val reason = options.string("reason") ?: defaultReason()
114
+ val allowDeviceCredential =
115
+ options.hasKey("allowDeviceCredential") && options.getBoolean("allowDeviceCredential")
116
+ // Android 9 and 10 take the device credential only beside a weak
117
+ // biometric; the strong ones and a credential arrived together in 11.
118
+ val authenticators =
119
+ when {
120
+ !allowDeviceCredential -> BIOMETRIC_STRONG
121
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> BIOMETRIC_STRONG or DEVICE_CREDENTIAL
122
+ else -> BIOMETRIC_WEAK or DEVICE_CREDENTIAL
123
+ }
124
+ val status = BiometricManager.from(activity).canAuthenticate(authenticators)
125
+ if (status != BiometricManager.BIOMETRIC_SUCCESS) {
126
+ callback.invoke(unavailable(status))
127
+ return
128
+ }
129
+ val info =
130
+ BiometricPrompt.PromptInfo.Builder()
131
+ .setTitle(options.string("title") ?: appName())
132
+ .setSubtitle(reason)
133
+ .setAllowedAuthenticators(authenticators)
134
+ .apply {
135
+ // A prompt that offers the device credential has its own
136
+ // way out, and Android refuses a cancel button beside it.
137
+ if (!allowDeviceCredential) {
138
+ setNegativeButtonText(options.string("cancelLabel") ?: "Cancel")
139
+ }
140
+ }
141
+ .build()
142
+ prompt(info, null, callback) { callback.invoke(JavaOnlyMap()) }
143
+ }
144
+
145
+ /**
146
+ * The value stored under `key`, once the person confirms, as `{ value }`,
147
+ * or `{}` without prompting when there's none.
148
+ */
149
+ @LynxMethod
150
+ fun getItem(key: String, reason: String, callback: Callback) {
151
+ worker.execute {
152
+ val stored = preferences.getString(key, null)
153
+ if (stored == null) {
154
+ callback.invoke(JavaOnlyMap())
155
+ return@execute
156
+ }
157
+ val cipher =
158
+ try {
159
+ rsaCipher().apply { init(Cipher.DECRYPT_MODE, privateKey(), OAEP) }
160
+ } catch (e: KeyPermanentlyInvalidatedException) {
161
+ // A fingerprint or face enrolled since: nothing stored
162
+ // under the old pair can be read again.
163
+ forgetEverything()
164
+ callback.invoke(JavaOnlyMap())
165
+ return@execute
166
+ } catch (e: Exception) {
167
+ callback.invoke(failed(e))
168
+ return@execute
169
+ }
170
+ val info =
171
+ BiometricPrompt.PromptInfo.Builder()
172
+ .setTitle(appName())
173
+ .setSubtitle(reason.ifEmpty { defaultReason() })
174
+ .setAllowedAuthenticators(BIOMETRIC_STRONG)
175
+ .setNegativeButtonText("Cancel")
176
+ .build()
177
+ main.post {
178
+ prompt(info, BiometricPrompt.CryptoObject(cipher), callback) { result ->
179
+ val unlocked = result.cryptoObject?.cipher ?: return@prompt callback.invoke(failed(null))
180
+ worker.execute {
181
+ callback.invoke(
182
+ try {
183
+ JavaOnlyMap.from(mapOf("value" to open(key, stored, unlocked)))
184
+ } catch (e: Exception) {
185
+ failed(e)
186
+ },
187
+ )
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+
194
+ /** Stores `value` under `key`, in place of what was there. Doesn't prompt. */
195
+ @LynxMethod
196
+ fun setItem(key: String, value: String, callback: Callback) {
197
+ worker.execute {
198
+ callback.invoke(
199
+ try {
200
+ val status = BiometricManager.from(activity).canAuthenticate(BIOMETRIC_STRONG)
201
+ if (activity.getSystemService(KeyguardManager::class.java)?.isDeviceSecure != true) {
202
+ // The Keystore makes no biometric key without a lock
203
+ // screen.
204
+ error("unavailable", "Set a screen lock to keep values behind biometrics.")
205
+ } else if (status != BiometricManager.BIOMETRIC_SUCCESS) {
206
+ // Nor without a strong biometric enrolled: a value
207
+ // nobody can unlock is no use.
208
+ unavailable(status)
209
+ } else {
210
+ val sealed = seal(key, value)
211
+ if (preferences.edit().putString(key, sealed).commit()) {
212
+ JavaOnlyMap()
213
+ } else {
214
+ error("failed", "The value couldn't be written to disk.")
215
+ }
216
+ }
217
+ } catch (e: Exception) {
218
+ failed(e)
219
+ },
220
+ )
221
+ }
222
+ }
223
+
224
+ @LynxMethod
225
+ fun removeItem(key: String, callback: Callback) {
226
+ worker.execute { callback.invoke(committed(preferences.edit().remove(key).commit())) }
227
+ }
228
+
229
+ @LynxMethod
230
+ fun clear(callback: Callback) {
231
+ worker.execute { callback.invoke(committed(preferences.edit().clear().commit())) }
232
+ }
233
+
234
+ /**
235
+ * `{}` once a removal is on disk, or why not: one that stayed in memory
236
+ * only would bring the value back when the app next starts.
237
+ */
238
+ private fun committed(onDisk: Boolean) =
239
+ if (onDisk) JavaOnlyMap() else error("failed", "The removal couldn't be written to disk.")
240
+
241
+ /**
242
+ * Shows a prompt on the main thread, and calls [succeeded] once the person
243
+ * is confirmed, or back with why not.
244
+ */
245
+ private fun prompt(
246
+ info: BiometricPrompt.PromptInfo,
247
+ crypto: BiometricPrompt.CryptoObject?,
248
+ callback: Callback,
249
+ succeeded: (BiometricPrompt.AuthenticationResult) -> Unit,
250
+ ) {
251
+ main.post {
252
+ if (prompting) {
253
+ callback.invoke(error("failed", "A biometric prompt is already open."))
254
+ return@post
255
+ }
256
+ prompting = true
257
+ val prompt =
258
+ BiometricPrompt(
259
+ activity,
260
+ ContextCompat.getMainExecutor(activity),
261
+ object : BiometricPrompt.AuthenticationCallback() {
262
+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
263
+ prompting = false
264
+ succeeded(result)
265
+ }
266
+
267
+ // A finger that didn't match leaves the prompt open
268
+ // for another try, so onAuthenticationFailed has
269
+ // nothing to report.
270
+ override fun onAuthenticationError(code: Int, message: CharSequence) {
271
+ prompting = false
272
+ callback.invoke(error(errorCode(code), message.toString()))
273
+ }
274
+ },
275
+ )
276
+ try {
277
+ if (crypto == null) prompt.authenticate(info) else prompt.authenticate(info, crypto)
278
+ } catch (e: Exception) {
279
+ // Such as an activity that's already saved its state.
280
+ prompting = false
281
+ callback.invoke(failed(e))
282
+ }
283
+ }
284
+ }
285
+
286
+ private fun seal(key: String, value: String): String {
287
+ val dataKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey()
288
+ val aes = Cipher.getInstance(AES)
289
+ aes.init(Cipher.ENCRYPT_MODE, dataKey)
290
+ aes.updateAAD(key.toByteArray())
291
+ val sealedValue = aes.iv + aes.doFinal(value.toByteArray())
292
+ val rsa = rsaCipher()
293
+ rsa.init(Cipher.ENCRYPT_MODE, publicKey(), OAEP)
294
+ val wrapped = rsa.doFinal(dataKey.encoded)
295
+ return Base64.encodeToString(wrapped + sealedValue, Base64.NO_WRAP)
296
+ }
297
+
298
+ private fun open(key: String, stored: String, unlocked: Cipher): String {
299
+ val sealed = Base64.decode(stored, Base64.NO_WRAP)
300
+ val dataKey = SecretKeySpec(unlocked.doFinal(sealed, 0, WRAPPED_BYTES), "AES")
301
+ val aes = Cipher.getInstance(AES)
302
+ aes.init(Cipher.DECRYPT_MODE, dataKey, GCMParameterSpec(TAG_BITS, sealed, WRAPPED_BYTES, IV_BYTES))
303
+ aes.updateAAD(key.toByteArray())
304
+ val start = WRAPPED_BYTES + IV_BYTES
305
+ return String(aes.doFinal(sealed, start, sealed.size - start))
306
+ }
307
+
308
+ private fun keyStore() = KeyStore.getInstance(KEYSTORE).apply { load(null) }
309
+
310
+ private fun privateKey(): PrivateKey =
311
+ keyStore().getKey(KEY_ALIAS, null) as? PrivateKey
312
+ ?: throw KeyPermanentlyInvalidatedException("The key is gone.")
313
+
314
+ /**
315
+ * The pair's public key, made the first time a value is stored, as a
316
+ * plain key outside the Keystore: the Keystore's own copy refuses OAEP's
317
+ * SHA-1 mask on some versions, and a public key needs no protecting.
318
+ *
319
+ * A fingerprint or face enrolled since invalidates the private key but
320
+ * not the public one, which would still seal a value nobody could open:
321
+ * the pair is checked first, and an invalid one is replaced, with the
322
+ * values it sealed, before the new value is sealed.
323
+ */
324
+ private fun publicKey(): PublicKey {
325
+ if (keyStore().containsAlias(KEY_ALIAS)) {
326
+ try {
327
+ // Needs no biometric: only using the key does.
328
+ rsaCipher().init(Cipher.DECRYPT_MODE, privateKey(), OAEP)
329
+ } catch (_: KeyPermanentlyInvalidatedException) {
330
+ forgetEverything()
331
+ }
332
+ }
333
+ val stored =
334
+ keyStore().getCertificate(KEY_ALIAS)?.publicKey
335
+ ?: KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, KEYSTORE)
336
+ .apply {
337
+ initialize(
338
+ KeyGenParameterSpec.Builder(
339
+ KEY_ALIAS,
340
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
341
+ )
342
+ .setKeySize(2048)
343
+ .setDigests(KeyProperties.DIGEST_SHA256)
344
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
345
+ .setUserAuthenticationRequired(true)
346
+ .setInvalidatedByBiometricEnrollment(true)
347
+ .apply {
348
+ // Each use, with a strong biometric only.
349
+ // Older versions do that by default.
350
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
351
+ setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
352
+ }
353
+ }
354
+ .build(),
355
+ )
356
+ }
357
+ .generateKeyPair()
358
+ .public
359
+ return KeyFactory.getInstance(stored.algorithm).generatePublic(X509EncodedKeySpec(stored.encoded))
360
+ }
361
+
362
+ private fun forgetEverything() {
363
+ preferences.edit().clear().commit()
364
+ try {
365
+ keyStore().deleteEntry(KEY_ALIAS)
366
+ } catch (_: Exception) {
367
+ // Already gone.
368
+ }
369
+ }
370
+
371
+ private fun appName(): String = activity.applicationInfo.loadLabel(activity.packageManager).toString()
372
+
373
+ /** angular.json's `permissions.biometrics`, from res/values/biometrics.xml. */
374
+ private fun defaultReason(): String = activity.getString(R.string.angular_lynx_biometrics_reason)
375
+
376
+ private fun ReadableMap.string(name: String): String? =
377
+ if (hasKey(name)) getString(name)?.takeIf { it.isNotEmpty() } else null
378
+
379
+ private fun error(code: String, message: String) =
380
+ JavaOnlyMap.from(mapOf("error" to code, "message" to message))
381
+
382
+ private fun failed(e: Exception?) =
383
+ error("failed", e?.message ?: "The person couldn't be confirmed.")
384
+
385
+ private fun unavailable(status: Int) =
386
+ when (status) {
387
+ BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->
388
+ error("notEnrolled", "No fingerprint or face is set up on this phone.")
389
+ else -> error("unavailable", "This phone can't confirm the person with biometrics.")
390
+ }
391
+
392
+ private fun errorCode(code: Int) =
393
+ when (code) {
394
+ BiometricPrompt.ERROR_USER_CANCELED,
395
+ BiometricPrompt.ERROR_NEGATIVE_BUTTON,
396
+ BiometricPrompt.ERROR_CANCELED,
397
+ -> "canceled"
398
+ BiometricPrompt.ERROR_LOCKOUT, BiometricPrompt.ERROR_LOCKOUT_PERMANENT -> "lockout"
399
+ BiometricPrompt.ERROR_NO_BIOMETRICS -> "notEnrolled"
400
+ BiometricPrompt.ERROR_HW_NOT_PRESENT,
401
+ BiometricPrompt.ERROR_HW_UNAVAILABLE,
402
+ BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL,
403
+ BiometricPrompt.ERROR_SECURITY_UPDATE_REQUIRED,
404
+ -> "unavailable"
405
+ else -> "failed"
406
+ }
407
+
408
+ companion object {
409
+ const val NAME = "AngularLynxBiometrics"
410
+ /** Also named in res/xml/backup_rules.xml and data_extraction_rules.xml. */
411
+ const val FILE = "angular_lynx_biometric_storage"
412
+ private const val KEYSTORE = "AndroidKeyStore"
413
+ private const val KEY_ALIAS = "angular_lynx_biometric_storage"
414
+ private const val RSA = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"
415
+ private const val AES = "AES/GCM/NoPadding"
416
+ /** A 2048-bit RSA key's output. */
417
+ private const val WRAPPED_BYTES = 256
418
+ private const val IV_BYTES = 12
419
+ private const val TAG_BITS = 128
420
+
421
+ /**
422
+ * OAEP with SHA-256, and SHA-1 for its mask, which is the only one
423
+ * the Keystore takes on every version: the same on both sides.
424
+ */
425
+ private val OAEP =
426
+ OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)
427
+
428
+ private fun rsaCipher(): Cipher = Cipher.getInstance(RSA)
429
+
430
+ /** One thread for every LynxView's module, so calls run in order. */
431
+ private val worker = Executors.newSingleThreadExecutor()
432
+ }
433
+ }
@@ -0,0 +1,98 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.Color
5
+ import android.graphics.Paint
6
+ import android.graphics.PorterDuff
7
+ import android.graphics.Rect
8
+ import android.graphics.SurfaceTexture
9
+ import android.util.Log
10
+ import android.view.Surface
11
+
12
+ /**
13
+ * Shows a bitmap in a canvas's view, for the contexts whose pixels are an
14
+ * `android.graphics.Bitmap`: a 2D context's (Canvas2DContext) and a
15
+ * bitmaprenderer's ImageBitmap (BitmapRendererContext). It copies the bitmap
16
+ * into the TextureView's surface with `lockHardwareCanvas()`, scaled to its
17
+ * size, as a canvas's bitmap is to its CSS size, and keeps the Surface it
18
+ * made of the view's SurfaceTexture.
19
+ *
20
+ * It isn't locked: its context calls it under its own lock, which keeps
21
+ * Lynx's engine thread, which draws, apart from the UI thread, where the
22
+ * surface comes and goes.
23
+ */
24
+ internal class BitmapPresenter(private val tag: String) {
25
+ /** The view frames are shown in, or null. */
26
+ var view: CanvasUI? = null
27
+ private set
28
+ private var surface: Surface? = null
29
+ private var surfaceTexture: SurfaceTexture? = null
30
+
31
+ /** Something was to be shown and wasn't yet, waiting for a surface. */
32
+ private var framePending = false
33
+ private val paint = Paint(Paint.FILTER_BITMAP_FLAG)
34
+
35
+ /**
36
+ * Shows frames in [canvas], see-through unless [opaque]. False when it's
37
+ * the view they're shown in already.
38
+ */
39
+ fun attach(canvas: CanvasUI?, opaque: Boolean): Boolean {
40
+ if (view === canvas) return false
41
+ view = canvas
42
+ canvas?.setOpaque(opaque)
43
+ return true
44
+ }
45
+
46
+ /**
47
+ * The view's surface came, went or changed size. True when a frame is
48
+ * waiting to be shown: a new surface shows nothing until it's drawn to.
49
+ */
50
+ fun surfaceChanged(): Boolean {
51
+ val texture = view?.surface
52
+ if (texture !== surfaceTexture) {
53
+ release()
54
+ if (texture != null) {
55
+ surface = Surface(texture)
56
+ surfaceTexture = texture
57
+ framePending = true
58
+ }
59
+ }
60
+ return framePending
61
+ }
62
+
63
+ /**
64
+ * Copies [bitmap] into the view's surface, scaled to its size, over
65
+ * [background] (transparent, or black for a canvas without alpha that
66
+ * shows no bitmap). It waits for a surface when there's none.
67
+ */
68
+ fun present(bitmap: Bitmap?, background: Int = Color.TRANSPARENT) {
69
+ val target = surface
70
+ if (target == null || !target.isValid) {
71
+ framePending = true
72
+ return
73
+ }
74
+ try {
75
+ val c = target.lockHardwareCanvas()
76
+ try {
77
+ c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
78
+ if (background != Color.TRANSPARENT) c.drawColor(background)
79
+ bitmap?.let { c.drawBitmap(it, null, Rect(0, 0, c.width, c.height), paint) }
80
+ } finally {
81
+ target.unlockCanvasAndPost(c)
82
+ }
83
+ framePending = false
84
+ } catch (error: RuntimeException) {
85
+ // The surface went as it was drawn to: it's drawn again when
86
+ // the next one comes.
87
+ Log.w(tag, "Could not show the canvas: ${error.message}")
88
+ framePending = true
89
+ }
90
+ }
91
+
92
+ /** Lets go of the surface it made. */
93
+ fun release() {
94
+ surface?.release()
95
+ surface = null
96
+ surfaceTexture = null
97
+ }
98
+ }