@blotch/angular-lynx-native 22.2.5 → 22.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,8 @@ Both are one full-screen `LynxView` running `main.lynx.bundle`; Angular Router d
19
19
 
20
20
  Both send the same global props, which the runtime's services read: `platform`, `theme` (again whenever the phone switches between light and dark), `appLocale` (the phone's language as a BCP 47 tag), `isNotchScreen`, the safe-area insets `safeAreaTop`, `safeAreaBottom`, `safeAreaLeft` and `safeAreaRight`, `osVersion` (which Lynx leaves out of the main thread's `SystemInfo`), and the accessibility settings `reduceMotion`, `reduceTransparency` (iOS only) and `increaseContrast`, again whenever the user changes one. Android 12 and later also send `dynamicColors`, the wallpaper's Material 3 color roles in light and dark (`DynamicColors.kt`), again when the user changes their wallpaper or colors. Lynx Explorer sends `theme` and `isNotchScreen` too, but no `appLocale`, `osVersion` or accessibility settings. See [`templates/android/README.md`](templates/android/README.md) for the Android shell's details.
21
21
 
22
+ Both register the native modules the runtime's services call, which Lynx Explorer doesn't have: `AngularLynxWebAuth` (`WebAuthModule.swift`, `WebAuthModule.kt`) opens `LynxWebAuthSession`'s sign-in page, in `ASWebAuthenticationSession` on iOS and a Custom Tab on Android, and returns the URL it redirects to. `AngularLynxLocalStorage` (`LocalStorageModule.swift`, `LocalStorageModule.kt`) keeps `LynxLocalStorage`'s values in a `UserDefaults` suite and a `SharedPreferences` file of their own. `AngularLynxSecureStorage` (`SecureStorageModule.swift`, `SecureStorageModule.kt`) keeps `LynxSecureStorage`'s in the Keychain on iOS and, on Android, in `SharedPreferences`, each value encrypted with AES-GCM by an Android Keystore key, a file Auto Backup leaves out (`res/xml/backup_rules.xml`, `data_extraction_rules.xml`). Android also has `AngularLynxShell`, for the back button.
23
+
22
24
  Both link Lynx's XElement library, which holds `<input>`, `<textarea>`, `<overlay>`, `<svg>`, `<blur-view>`, `<viewpager>`, `<refresh>`, the `<scroll-coordinator>` family, `<webview>` and `<video>`. Lynx's core doesn't include these, and a host that doesn't register them renders nothing for those tags (on Android, nothing after them either). XElement's AnimaX and Markdown elements are left out: the runtime doesn't support them. On iOS, `<blur-view>` is XElement's with more of UIKit in it (`App/BlurView.swift`): a `blur-material` attribute for UIKit's adaptive blur materials, which the glass components draw their design before iOS 26 on (Lynx's blur-view has only the styles from before iOS 13); Liquid Glass that materializes, dissolves and eases between effects inside a `glass-container`, where Lynx's sets its effect at once; and a `glass-effect-id` attribute that pairs two glass shapes across a change so one morphs into the other (`App/GlassTransitions.swift`).
23
25
 
24
26
  | | iOS | Android |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-native",
3
- "version": "22.2.5",
3
+ "version": "22.2.7",
4
4
  "description": "Builds AngularLynx apps into iOS and Android binaries",
5
5
  "homepage": "https://github.com/Blotch-Smart-Frames/AngularLynx#readme",
6
6
  "bugs": {
@@ -34,6 +34,19 @@ Build commands and outputs (no flavors, so the names are fixed):
34
34
 
35
35
  Back is off by default, so it leaves the app like any root screen. The runtime turns it on while the Router has history by calling `NativeModules.AngularLynxShell.setBackHandlerEnabled(true)`, and off again on the first screen (`LynxBackButton` in `packages/runtime/src/lib/router/lynx-back-button.ts`, which `provideRouter()` starts; the call goes through the background thread, where `NativeModules` lives). While it's on, a back press sends the global event `angularLynxBack` instead, which the runtime turns into `Location.back()`. The app has to say beforehand because Android decides synchronously, at the start of the gesture, whether an app handles back (predictive back animates differently). Layer 6's `native/back-button.yaml` checks both ends.
36
36
 
37
+ ## Web sign-in
38
+
39
+ `NativeModules.AngularLynxWebAuth.start(request, callback)` (`WebAuthModule.kt`, behind the runtime's `LynxWebAuthSession`) opens `request.url` in a Custom Tab (`androidx.browser`). The page's redirect to `request.callbackScheme` comes back as a deep link: the activity is `singleTask`, so the intent reaches the open one in `onNewIntent`, which hands the URL to the callback, and starting it closes the Custom Tab above it. That's why the scheme has to be in the app's `deepLinkSchemes`. Android says nothing when a Custom Tab is closed, so the activity resuming with a session still open, after having gone behind the tab, means the person canceled. iOS's `WebAuthModule.swift` reports the same results through `ASWebAuthenticationSession`.
40
+
41
+ ## Storage
42
+
43
+ `NativeModules.AngularLynxLocalStorage` and `NativeModules.AngularLynxSecureStorage` (`LocalStorageModule.kt` and `SecureStorageModule.kt`, behind the runtime's `LynxLocalStorage` and `LynxSecureStorage`) keep string values, which the runtime stores as JSON, each in a `SharedPreferences` file of its own. Each method calls back once with `{ value }`, `{}` or `{ error }`.
44
+
45
+ - **Secure values are encrypted with AES-GCM** by a key the Android Keystore makes the first time and never lets out, with the value's key as the associated data. Android's `EncryptedSharedPreferences` did the same, but `androidx.security:security-crypto` is deprecated. The secure module works on one background thread shared by every LynxView, since the Keystore can be slow, so calls run in order.
46
+ - **Auto Backup leaves out the secure file** (`res/xml/backup_rules.xml` up to Android 11, `data_extraction_rules.xml` from 12): the key can't leave the device, so a restored copy couldn't be decrypted. A value that won't decrypt anyway is removed and read as none.
47
+
48
+ iOS's `LocalStorageModule.swift` uses a `UserDefaults` suite and `SecureStorageModule.swift` the Keychain, readable after the first unlock and never moved to another device.
49
+
37
50
  ## Global props
38
51
 
39
52
  `MainActivity.globalProps()` sends what the runtime reads and Lynx has no API for (see the package README), again on every configuration change and accessibility setting change.
@@ -47,6 +60,7 @@ Back is off by default, so it leaves the app like any root screen. The runtime t
47
60
  Pinned in `app/build.gradle.kts`, `build.gradle.kts` and `gradle/wrapper/gradle-wrapper.properties`:
48
61
 
49
62
  - Lynx 4.1.0 and PrimJS 4.1.1 (Maven Central), Fresco 2.3.0 (the version Lynx's image service is built against), OkHttp 4.12.
63
+ - `androidx.browser` 1.8.0, for the Custom Tabs `WebAuthModule` opens sign-in pages in.
50
64
  - Lynx's XElement 4.1.0 (`<input>`, `<textarea>`, `<overlay>`, `<svg>`, `<blur-view>`, `<viewpager>`, `<refresh>`, the `<scroll-coordinator>` family, `<webview>`, `<video>`), without its AnimaX and Markdown modules, which the runtime doesn't support. `MainActivity` registers the elements with `XElementBehaviors`. XElement depends on appcompat and material 1.0.0, whose vectordrawable libraries share a namespace that AGP 9 rejects, so appcompat 1.7.1 and material 1.12.0 are pinned.
51
65
  - AGP 9.4.1 with its built-in Kotlin, Gradle 9.6.1 (AGP 9.4's minimum), JDK 17 or newer.
52
66
  - `compileSdk` and `targetSdk` 36, `minSdk` 24. Google Play raises its target API requirement every August; bump `targetSdk` with it.
@@ -118,6 +118,8 @@ android {
118
118
  dependencies {
119
119
  implementation("androidx.activity:activity-ktx:1.10.1")
120
120
  implementation("androidx.core:core-ktx:1.16.0")
121
+ // Custom Tabs, which WebAuthModule opens sign-in pages in.
122
+ implementation("androidx.browser:browser:1.8.0")
121
123
 
122
124
  // The Lynx engine, its JavaScript runtime (PrimJS) and its JS SDK.
123
125
  implementation("org.lynxsdk.lynx:lynx:$lynxVersion")
@@ -1,18 +1,26 @@
1
1
  <?xml version="1.0" encoding="utf-8"?>
2
- <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+ xmlns:tools="http://schemas.android.com/tools">
3
4
 
4
5
  <!-- fetch() and XMLHttpRequest go through Lynx's HTTP service. -->
5
6
  <uses-permission android:name="android.permission.INTERNET" />
6
7
  <!-- angular-lynx:permissions -->
7
8
 
9
+ <!--
10
+ Auto Backup leaves out LynxSecureStorage's file (SecureStorageModule):
11
+ dataExtractionRules from Android 12, fullBackupContent before.
12
+ -->
8
13
  <application
9
14
  android:name=".ShellApplication"
10
15
  android:allowBackup="true"
16
+ android:dataExtractionRules="@xml/data_extraction_rules"
17
+ android:fullBackupContent="@xml/backup_rules"
11
18
  android:icon="@mipmap/ic_launcher"
12
19
  android:label="@string/app_name"
13
20
  android:networkSecurityConfig="@xml/network_security_config"
14
21
  android:supportsRtl="true"
15
- android:theme="@style/Theme.AngularLynxShell">
22
+ android:theme="@style/Theme.AngularLynxShell"
23
+ tools:targetApi="31">
16
24
  <!--
17
25
  One activity holding one LynxView; Angular Router does all navigation
18
26
  inside it. configChanges keeps the activity (and the running Angular
@@ -0,0 +1,51 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import com.lynx.jsbridge.LynxMethod
5
+ import com.lynx.jsbridge.LynxModule
6
+ import com.lynx.react.bridge.Callback
7
+ import com.lynx.react.bridge.JavaOnlyMap
8
+
9
+ /**
10
+ * The native module behind the runtime's `LynxLocalStorage`, which calls it
11
+ * as `NativeModules.AngularLynxLocalStorage` (from the background thread,
12
+ * where NativeModules lives).
13
+ *
14
+ * Values are strings (the runtime stores JSON) in a SharedPreferences file of
15
+ * their own, so `clear` removes only them. Each method calls back once with
16
+ * `{ value }` or `{}`, as the iOS module does.
17
+ */
18
+ class LocalStorageModule(context: Context, param: Any?) : LynxModule(context, param) {
19
+ private val preferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
20
+
21
+ @LynxMethod
22
+ fun getItem(key: String, callback: Callback) {
23
+ val value = preferences.getString(key, null)
24
+ callback.invoke(if (value != null) JavaOnlyMap.from(mapOf("value" to value)) else JavaOnlyMap())
25
+ }
26
+
27
+ // apply() writes to disk in the background, and Android finishes the
28
+ // write before the activity stops, so the app can't be closed before it.
29
+ @LynxMethod
30
+ fun setItem(key: String, value: String, callback: Callback) {
31
+ preferences.edit().putString(key, value).apply()
32
+ callback.invoke(JavaOnlyMap())
33
+ }
34
+
35
+ @LynxMethod
36
+ fun removeItem(key: String, callback: Callback) {
37
+ preferences.edit().remove(key).apply()
38
+ callback.invoke(JavaOnlyMap())
39
+ }
40
+
41
+ @LynxMethod
42
+ fun clear(callback: Callback) {
43
+ preferences.edit().clear().apply()
44
+ callback.invoke(JavaOnlyMap())
45
+ }
46
+
47
+ companion object {
48
+ const val NAME = "AngularLynxLocalStorage"
49
+ const val FILE = "angular_lynx_local_storage"
50
+ }
51
+ }
@@ -1,9 +1,12 @@
1
1
  package dev.angularlynx.shell
2
2
 
3
3
  import android.app.UiModeManager
4
+ import android.content.ActivityNotFoundException
5
+ import android.content.Intent
4
6
  import android.content.res.Configuration
5
7
  import android.database.ContentObserver
6
8
  import android.graphics.drawable.ColorDrawable
9
+ import android.net.Uri
7
10
  import android.os.Build
8
11
  import android.os.Bundle
9
12
  import android.os.Handler
@@ -15,6 +18,7 @@ import android.widget.FrameLayout
15
18
  import androidx.activity.ComponentActivity
16
19
  import androidx.activity.OnBackPressedCallback
17
20
  import androidx.activity.enableEdgeToEdge
21
+ import androidx.browser.customtabs.CustomTabsIntent
18
22
  import androidx.core.graphics.Insets
19
23
  import androidx.core.os.ConfigurationCompat
20
24
  import androidx.core.view.ViewCompat
@@ -31,7 +35,7 @@ import com.lynx.xelement.XElementBehaviors
31
35
  * The whole app: one full-screen LynxView running the Angular app. Angular
32
36
  * Router navigates inside it, so there is no native navigation stack.
33
37
  */
34
- class MainActivity : ComponentActivity(), ShellModule.Host {
38
+ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
35
39
  private lateinit var lynxView: LynxView
36
40
 
37
41
  // The system bar and cutout insets, and whether the screen has a cutout,
@@ -57,6 +61,13 @@ class MainActivity : ComponentActivity(), ShellModule.Host {
57
61
  }
58
62
  }
59
63
 
64
+ // The open sign-in (see WebAuthModule): the scheme its page returns to,
65
+ // who to tell, and whether the app has gone behind the Custom Tab yet.
66
+ private class WebAuthSession(val scheme: String, val done: (WebAuthModule.Result) -> Unit) {
67
+ var opened = false
68
+ }
69
+ private var webAuthSession: WebAuthSession? = null
70
+
60
71
  override fun onCreate(savedInstanceState: Bundle?) {
61
72
  // Android 15+ always draws apps edge to edge; opting in on older
62
73
  // versions too keeps the layout the same everywhere.
@@ -70,6 +81,9 @@ class MainActivity : ComponentActivity(), ShellModule.Host {
70
81
  setEnableGenericResourceFetcher(LynxBooleanOption.TRUE)
71
82
  setGenericResourceFetcher(AssetGenericResourceFetcher(this@MainActivity))
72
83
  registerModule(ShellModule.NAME, ShellModule::class.java, this@MainActivity)
84
+ registerModule(WebAuthModule.NAME, WebAuthModule::class.java, this@MainActivity)
85
+ registerModule(LocalStorageModule.NAME, LocalStorageModule::class.java, null)
86
+ registerModule(SecureStorageModule.NAME, SecureStorageModule::class.java, null)
73
87
  // Lynx's core has no <input>, <overlay>, <svg>, <blur-view> etc.;
74
88
  // these come from XElement (see app/build.gradle.kts). Lynx
75
89
  // Explorer registers them the same way.
@@ -136,6 +150,33 @@ class MainActivity : ComponentActivity(), ShellModule.Host {
136
150
  backHandler.isEnabled = enabled
137
151
  }
138
152
 
153
+ override fun startWebAuthSession(url: Uri, callbackScheme: String, done: (WebAuthModule.Result) -> Unit) {
154
+ if (webAuthSession != null) {
155
+ done(WebAuthModule.Result.Failed("A sign-in is already open."))
156
+ return
157
+ }
158
+ val session = WebAuthSession(callbackScheme.lowercase(), done)
159
+ webAuthSession = session
160
+ try {
161
+ CustomTabsIntent.Builder().build().launchUrl(this, url)
162
+ } catch (_: ActivityNotFoundException) {
163
+ webAuthSession = null
164
+ done(WebAuthModule.Result.Failed("No browser can open the sign-in page."))
165
+ }
166
+ }
167
+
168
+ // The page's redirect to the callback scheme. The activity is singleTask,
169
+ // so the deep link comes back to this one, which closes the Custom Tab
170
+ // above it. It arrives before onResume, which then finds no session open.
171
+ override fun onNewIntent(intent: Intent) {
172
+ super.onNewIntent(intent)
173
+ val url = intent.data ?: return
174
+ val session = webAuthSession ?: return
175
+ if (url.scheme?.lowercase() != session.scheme) return
176
+ webAuthSession = null
177
+ session.done(WebAuthModule.Result.Returned(url.toString()))
178
+ }
179
+
139
180
  // The manifest's configChanges keeps the activity, and the running app,
140
181
  // through a dark mode switch, so the new theme is sent from here. A
141
182
  // language change still restarts the activity, which sends the new
@@ -212,10 +253,17 @@ class MainActivity : ComponentActivity(), ShellModule.Host {
212
253
  override fun onResume() {
213
254
  super.onResume()
214
255
  lynxView.onEnterForeground()
256
+ // Back from a Custom Tab without its redirect: the person closed it.
257
+ // Android says nothing else when a Custom Tab closes.
258
+ webAuthSession?.takeIf { it.opened }?.let {
259
+ webAuthSession = null
260
+ it.done(WebAuthModule.Result.Canceled)
261
+ }
215
262
  }
216
263
 
217
264
  override fun onPause() {
218
265
  lynxView.onEnterBackground()
266
+ webAuthSession?.opened = true
219
267
  super.onPause()
220
268
  }
221
269
 
@@ -0,0 +1,149 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import android.content.SharedPreferences
5
+ import android.security.keystore.KeyGenParameterSpec
6
+ import android.security.keystore.KeyProperties
7
+ import android.util.Base64
8
+ import com.lynx.jsbridge.LynxMethod
9
+ import com.lynx.jsbridge.LynxModule
10
+ import com.lynx.react.bridge.Callback
11
+ import com.lynx.react.bridge.JavaOnlyMap
12
+ import java.security.GeneralSecurityException
13
+ import java.security.KeyStore
14
+ import java.util.concurrent.Executors
15
+ import javax.crypto.Cipher
16
+ import javax.crypto.KeyGenerator
17
+ import javax.crypto.SecretKey
18
+ import javax.crypto.spec.GCMParameterSpec
19
+
20
+ /**
21
+ * The native module behind the runtime's `LynxSecureStorage`, which calls it
22
+ * as `NativeModules.AngularLynxSecureStorage` (from the background thread,
23
+ * where NativeModules lives).
24
+ *
25
+ * Values are strings (the runtime stores JSON), each encrypted with AES-GCM
26
+ * by a key the Android Keystore holds and never lets out, and kept in a
27
+ * SharedPreferences file of their own. The value's key is the cipher's
28
+ * associated data, so a value copied to another key won't decrypt. Android's
29
+ * EncryptedSharedPreferences did the same, but its library is deprecated.
30
+ *
31
+ * Auto Backup leaves the file out (res/xml/backup_rules.xml and
32
+ * data_extraction_rules.xml): the Keystore key never leaves the device, so a
33
+ * restored copy couldn't be read. Each method calls back once with
34
+ * `{ value }`, `{}` or `{ error }`, as the iOS module does.
35
+ */
36
+ class SecureStorageModule(context: Context, param: Any?) : LynxModule(context, param) {
37
+ private val preferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
38
+
39
+ @LynxMethod
40
+ fun getItem(key: String, callback: Callback) = respond(callback) {
41
+ val stored = preferences.getString(key, null) ?: return@respond null
42
+ try {
43
+ decrypt(key, stored)
44
+ } catch (e: Exception) {
45
+ // A value that won't decrypt, as when the Keystore lost the key,
46
+ // can never be read, so it's as good as none.
47
+ if (e !is GeneralSecurityException && e !is IllegalArgumentException) throw e
48
+ preferences.edit().remove(key).commit()
49
+ null
50
+ }
51
+ }
52
+
53
+ @LynxMethod
54
+ fun setItem(key: String, value: String, callback: Callback) = respond(callback) {
55
+ write { putString(key, encrypt(key, value)) }
56
+ }
57
+
58
+ @LynxMethod
59
+ fun removeItem(key: String, callback: Callback) = respond(callback) {
60
+ write { remove(key) }
61
+ }
62
+
63
+ @LynxMethod
64
+ fun clear(callback: Callback) = respond(callback) {
65
+ write { clear() }
66
+ }
67
+
68
+ /**
69
+ * Runs [work] off the JavaScript thread, since the Keystore can be slow,
70
+ * and calls back with the value it returns, or with why it failed.
71
+ */
72
+ private fun respond(callback: Callback, work: () -> String?) {
73
+ executor.execute {
74
+ val result = try {
75
+ work()?.let { mapOf("value" to it) } ?: emptyMap()
76
+ } catch (e: Exception) {
77
+ mapOf("error" to (e.message ?: e.toString()))
78
+ }
79
+ callback.invoke(JavaOnlyMap.from(result))
80
+ }
81
+ }
82
+
83
+ /** Commits an edit, so the callback only says it's stored once it's on disk. */
84
+ private fun write(edit: SharedPreferences.Editor.() -> Unit): String? {
85
+ val editor = preferences.edit()
86
+ editor.edit()
87
+ if (!editor.commit()) {
88
+ error("The value couldn't be written to disk.")
89
+ }
90
+ return null
91
+ }
92
+
93
+ private fun encrypt(key: String, value: String): String {
94
+ val cipher = Cipher.getInstance(TRANSFORMATION)
95
+ // The Keystore picks a random IV for each value.
96
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey())
97
+ cipher.updateAAD(key.toByteArray())
98
+ val sealed = cipher.iv + cipher.doFinal(value.toByteArray())
99
+ return Base64.encodeToString(sealed, Base64.NO_WRAP)
100
+ }
101
+
102
+ private fun decrypt(key: String, stored: String): String {
103
+ val sealed = Base64.decode(stored, Base64.NO_WRAP)
104
+ val cipher = Cipher.getInstance(TRANSFORMATION)
105
+ cipher.init(
106
+ Cipher.DECRYPT_MODE,
107
+ secretKey(),
108
+ GCMParameterSpec(TAG_BITS, sealed, 0, IV_BYTES),
109
+ )
110
+ cipher.updateAAD(key.toByteArray())
111
+ return String(cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES))
112
+ }
113
+
114
+ /** The Keystore's key, made the first time a value is stored. */
115
+ private fun secretKey(): SecretKey {
116
+ val keyStore = KeyStore.getInstance(KEYSTORE).apply { load(null) }
117
+ (keyStore.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
118
+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
119
+ generator.init(
120
+ KeyGenParameterSpec.Builder(
121
+ KEY_ALIAS,
122
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
123
+ )
124
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
125
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
126
+ .setKeySize(256)
127
+ .build(),
128
+ )
129
+ return generator.generateKey()
130
+ }
131
+
132
+ companion object {
133
+ const val NAME = "AngularLynxSecureStorage"
134
+ /** Also named in res/xml/backup_rules.xml and data_extraction_rules.xml. */
135
+ const val FILE = "angular_lynx_secure_storage"
136
+ private const val KEYSTORE = "AndroidKeyStore"
137
+ private const val KEY_ALIAS = "angular_lynx_secure_storage"
138
+ private const val TRANSFORMATION = "AES/GCM/NoPadding"
139
+ private const val IV_BYTES = 12
140
+ private const val TAG_BITS = 128
141
+
142
+ /**
143
+ * One thread for every LynxView's module, so calls run in the order
144
+ * they were made (a read sees the writes before it) and two can't
145
+ * both make the key.
146
+ */
147
+ private val executor = Executors.newSingleThreadExecutor()
148
+ }
149
+ }
@@ -0,0 +1,77 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import android.net.Uri
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import com.lynx.jsbridge.LynxMethod
8
+ import com.lynx.jsbridge.LynxModule
9
+ import com.lynx.react.bridge.Callback
10
+ import com.lynx.react.bridge.JavaOnlyMap
11
+ import com.lynx.react.bridge.ReadableMap
12
+
13
+ /**
14
+ * The native module behind the runtime's `LynxWebAuthSession`, which calls it
15
+ * as `NativeModules.AngularLynxWebAuth` (from the background thread, where
16
+ * NativeModules lives).
17
+ *
18
+ * Lynx has no popups or redirects, so a sign-in page can't run inside the
19
+ * app. The activity opens it in a Custom Tab instead, and the page's redirect
20
+ * to the callback scheme comes back to it as a deep link, which is why the
21
+ * scheme has to be one of the app's `deepLinkSchemes`.
22
+ */
23
+ class WebAuthModule(context: Context, param: Any?) : LynxModule(context, param) {
24
+ private val host = param as Host
25
+ private val main = Handler(Looper.getMainLooper())
26
+
27
+ interface Host {
28
+ /**
29
+ * Opens [url] and calls [done] once with the URL the page redirected
30
+ * to on [callbackScheme], or with why it didn't.
31
+ */
32
+ fun startWebAuthSession(url: Uri, callbackScheme: String, done: (Result) -> Unit)
33
+ }
34
+
35
+ /** How a session ended: the URL the page returned to, or why it didn't. */
36
+ sealed interface Result {
37
+ data class Returned(val url: String) : Result
38
+ data object Canceled : Result
39
+ data class Failed(val message: String) : Result
40
+ }
41
+
42
+ /**
43
+ * Calls back once with `{ url }` or `{ error, message }`, where `error` is
44
+ * `canceled` or `failed`, as the iOS module does.
45
+ */
46
+ @LynxMethod
47
+ fun start(request: ReadableMap, callback: Callback) {
48
+ val url = request.getString("url", "")
49
+ val scheme = request.getString("callbackScheme", "")
50
+ if (url.isEmpty() || scheme.isEmpty()) {
51
+ callback.invoke(failed("The sign-in needs a URL and a callback scheme."))
52
+ return
53
+ }
54
+ // Lynx calls modules off the main thread, and the activity starts the
55
+ // Custom Tab.
56
+ main.post {
57
+ host.startWebAuthSession(Uri.parse(url), scheme) { result ->
58
+ callback.invoke(
59
+ when (result) {
60
+ is Result.Returned -> JavaOnlyMap.from(mapOf("url" to result.url))
61
+ Result.Canceled -> JavaOnlyMap.from(
62
+ mapOf("error" to "canceled", "message" to "The sign-in was canceled."),
63
+ )
64
+ is Result.Failed -> failed(result.message)
65
+ },
66
+ )
67
+ }
68
+ }
69
+ }
70
+
71
+ private fun failed(message: String) =
72
+ JavaOnlyMap.from(mapOf("error" to "failed", "message" to message))
73
+
74
+ companion object {
75
+ const val NAME = "AngularLynxWebAuth"
76
+ }
77
+ }
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!--
3
+ Auto Backup up to Android 11 (data_extraction_rules.xml is Android 12's).
4
+ Everything is backed up but LynxSecureStorage's values: the Keystore key
5
+ that encrypts them never leaves the device, so a restored copy couldn't be
6
+ read (SecureStorageModule.kt).
7
+ -->
8
+ <full-backup-content>
9
+ <exclude domain="sharedpref" path="angular_lynx_secure_storage.xml" />
10
+ </full-backup-content>
@@ -0,0 +1,15 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!--
3
+ Backup and device transfer from Android 12 (backup_rules.xml is for older
4
+ versions). Everything goes but LynxSecureStorage's values: the Keystore key
5
+ that encrypts them never leaves the device, so a copy elsewhere couldn't be
6
+ read (SecureStorageModule.kt).
7
+ -->
8
+ <data-extraction-rules>
9
+ <cloud-backup>
10
+ <exclude domain="sharedpref" path="angular_lynx_secure_storage.xml" />
11
+ </cloud-backup>
12
+ <device-transfer>
13
+ <exclude domain="sharedpref" path="angular_lynx_secure_storage.xml" />
14
+ </device-transfer>
15
+ </data-extraction-rules>
@@ -0,0 +1,62 @@
1
+ import Foundation
2
+ import Lynx
3
+
4
+ /// The native module behind the runtime's `LynxLocalStorage`, which calls it
5
+ /// as `NativeModules.AngularLynxLocalStorage` (from the background thread,
6
+ /// where NativeModules lives).
7
+ ///
8
+ /// Values are strings (the runtime stores JSON) in a UserDefaults suite of
9
+ /// their own, so `clear` removes only them, and the app's other defaults
10
+ /// stay out of reach. Each method calls back once with `{ value }` or `{}`.
11
+ final class LocalStorageModule: NSObject, LynxModule {
12
+ static var name: String { "AngularLynxLocalStorage" }
13
+
14
+ static var methodLookup: [String: String] {
15
+ [
16
+ "getItem": NSStringFromSelector(#selector(getItem(_:callback:))),
17
+ "setItem": NSStringFromSelector(#selector(setItem(_:value:callback:))),
18
+ "removeItem": NSStringFromSelector(#selector(removeItem(_:callback:))),
19
+ "clear": NSStringFromSelector(#selector(clear(_:))),
20
+ ]
21
+ }
22
+
23
+ /// Any name but the app's bundle ID, which UserDefaults won't take.
24
+ private static let suite = "dev.angularlynx.storage"
25
+
26
+ // The suite name is valid, so this is never nil.
27
+ private let defaults = UserDefaults(suiteName: LocalStorageModule.suite)!
28
+
29
+ override init() {
30
+ super.init()
31
+ }
32
+
33
+ // Swift can't import an optional initializer as optional, so Lynx's
34
+ // initWithParam: is required here. Registered without a param, the module
35
+ // ignores it.
36
+ init(param: Any) {
37
+ super.init()
38
+ }
39
+
40
+ @objc func getItem(_ key: String, callback: @escaping LynxCallbackBlock) {
41
+ // Read the suite's own values: UserDefaults' lookups also search the
42
+ // global domain and the launch arguments, which would answer for keys
43
+ // such as AppleLanguages that the app never stored.
44
+ let value = defaults.persistentDomain(forName: Self.suite)?[key] as? String
45
+ callback(value.map { ["value": $0] } ?? [:])
46
+ }
47
+
48
+ @objc func setItem(_ key: String, value: String, callback: @escaping LynxCallbackBlock) {
49
+ defaults.set(value, forKey: key)
50
+ callback([:])
51
+ }
52
+
53
+ @objc func removeItem(_ key: String, callback: @escaping LynxCallbackBlock) {
54
+ defaults.removeObject(forKey: key)
55
+ callback([:])
56
+ }
57
+
58
+ @objc func clear(_ callback: @escaping LynxCallbackBlock) {
59
+ defaults.removePersistentDomain(forName: Self.suite)
60
+ callback([:])
61
+ }
62
+ }
@@ -13,8 +13,13 @@ final class LynxViewController: UIViewController {
13
13
 
14
14
  let fetcher = BundleResourceFetcher.shared
15
15
  let screenSize = UIScreen.main.bounds.size
16
+ // The shell's native modules, which the runtime's services call.
17
+ let config = LynxConfig(provider: LynxEnv.sharedInstance().config.templateProvider)
18
+ config.register(WebAuthModule.self)
19
+ config.register(LocalStorageModule.self)
20
+ config.register(SecureStorageModule.self)
16
21
  let lynxView = LynxView { builder in
17
- builder.config = LynxConfig(provider: LynxEnv.sharedInstance().config.templateProvider)
22
+ builder.config = config
18
23
  builder.screenSize = screenSize
19
24
  builder.fontScale = 1.0
20
25
  builder.enableGenericResourceFetcher = .true
@@ -0,0 +1,111 @@
1
+ import Foundation
2
+ import Lynx
3
+ import Security
4
+
5
+ /// The native module behind the runtime's `LynxSecureStorage`, which calls it
6
+ /// as `NativeModules.AngularLynxSecureStorage` (from the background thread,
7
+ /// where NativeModules lives).
8
+ ///
9
+ /// Values are strings (the runtime stores JSON) kept in the Keychain, as
10
+ /// generic passwords of one service, each under its key as the account.
11
+ /// They're readable once the phone has been unlocked after it starts, so a
12
+ /// token can be refreshed while the app is in the background, and never leave
13
+ /// the device, in a backup or otherwise. The Keychain keeps them when the app
14
+ /// is deleted, which the runtime's docs point out. Each method calls back once
15
+ /// with `{ value }`, `{}` or `{ error }`.
16
+ final class SecureStorageModule: NSObject, LynxModule {
17
+ static var name: String { "AngularLynxSecureStorage" }
18
+
19
+ static var methodLookup: [String: String] {
20
+ [
21
+ "getItem": NSStringFromSelector(#selector(getItem(_:callback:))),
22
+ "setItem": NSStringFromSelector(#selector(setItem(_:value:callback:))),
23
+ "removeItem": NSStringFromSelector(#selector(removeItem(_:callback:))),
24
+ "clear": NSStringFromSelector(#selector(clear(_:))),
25
+ ]
26
+ }
27
+
28
+ private let service = "\(Bundle.main.bundleIdentifier ?? "app").angular-lynx.secure-storage"
29
+
30
+ /// Keychain calls can block, so they run off the JavaScript thread, one at
31
+ /// a time and in the order they were made, so a read sees the writes
32
+ /// before it. Shared by every LynxView's module.
33
+ private static let queue = DispatchQueue(label: "dev.angularlynx.secure-storage")
34
+
35
+ override init() {
36
+ super.init()
37
+ }
38
+
39
+ // Swift can't import an optional initializer as optional, so Lynx's
40
+ // initWithParam: is required here. Registered without a param, the module
41
+ // ignores it.
42
+ init(param: Any) {
43
+ super.init()
44
+ }
45
+
46
+ @objc func getItem(_ key: String, callback: @escaping LynxCallbackBlock) {
47
+ Self.queue.async {
48
+ var query = self.query(key)
49
+ query[kSecReturnData as String] = true
50
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
51
+ var data: AnyObject?
52
+ let status = SecItemCopyMatching(query as CFDictionary, &data)
53
+ if status == errSecSuccess, let data = data as? Data,
54
+ let value = String(data: data, encoding: .utf8)
55
+ {
56
+ callback(["value": value])
57
+ } else if status == errSecSuccess || status == errSecItemNotFound {
58
+ callback([:])
59
+ } else {
60
+ callback(self.failure(status))
61
+ }
62
+ }
63
+ }
64
+
65
+ @objc func setItem(_ key: String, value: String, callback: @escaping LynxCallbackBlock) {
66
+ Self.queue.async {
67
+ let data = Data(value.utf8)
68
+ var status = SecItemUpdate(
69
+ self.query(key) as CFDictionary, [kSecValueData as String: data] as CFDictionary)
70
+ if status == errSecItemNotFound {
71
+ var item = self.query(key)
72
+ item[kSecValueData as String] = data
73
+ item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
74
+ status = SecItemAdd(item as CFDictionary, nil)
75
+ }
76
+ callback(status == errSecSuccess ? [:] : self.failure(status))
77
+ }
78
+ }
79
+
80
+ @objc func removeItem(_ key: String, callback: @escaping LynxCallbackBlock) {
81
+ Self.queue.async {
82
+ self.delete(self.query(key), callback)
83
+ }
84
+ }
85
+
86
+ @objc func clear(_ callback: @escaping LynxCallbackBlock) {
87
+ Self.queue.async {
88
+ self.delete(
89
+ [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: self.service],
90
+ callback)
91
+ }
92
+ }
93
+
94
+ private func query(_ key: String) -> [String: Any] {
95
+ [
96
+ kSecClass as String: kSecClassGenericPassword,
97
+ kSecAttrService as String: service,
98
+ kSecAttrAccount as String: key,
99
+ ]
100
+ }
101
+
102
+ /// Deletes every item `query` matches. None is fine too.
103
+ private func delete(_ query: [String: Any], _ callback: LynxCallbackBlock) {
104
+ let status = SecItemDelete(query as CFDictionary)
105
+ callback(status == errSecSuccess || status == errSecItemNotFound ? [:] : failure(status))
106
+ }
107
+
108
+ private func failure(_ status: OSStatus) -> [String: Any] {
109
+ ["error": SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)"]
110
+ }
111
+ }
@@ -0,0 +1,95 @@
1
+ import AuthenticationServices
2
+ import Lynx
3
+ import UIKit
4
+
5
+ /// The native module behind the runtime's `LynxWebAuthSession`, which calls it
6
+ /// as `NativeModules.AngularLynxWebAuth` (from the background thread, where
7
+ /// NativeModules lives).
8
+ ///
9
+ /// Lynx has no popups or redirects, so a sign-in page can't run inside the
10
+ /// app. ASWebAuthenticationSession opens it in Safari's sign-in sheet instead,
11
+ /// asking the person first, and ends when the page redirects to the callback
12
+ /// scheme. The scheme needn't be registered in Info.plist: the session catches
13
+ /// the redirect itself, so no other app can.
14
+ final class WebAuthModule: NSObject, LynxModule, ASWebAuthenticationPresentationContextProviding {
15
+ static var name: String { "AngularLynxWebAuth" }
16
+
17
+ static var methodLookup: [String: String] {
18
+ ["start": NSStringFromSelector(#selector(start(_:callback:)))]
19
+ }
20
+
21
+ /// The open session. Held until it ends: ASWebAuthenticationSession closes
22
+ /// its sheet when released.
23
+ private var session: ASWebAuthenticationSession?
24
+
25
+ override init() {
26
+ super.init()
27
+ }
28
+
29
+ // Swift can't import an optional initializer as optional, so Lynx's
30
+ // initWithParam: is required here. Registered without a param, the module
31
+ // ignores it.
32
+ init(param: Any) {
33
+ super.init()
34
+ }
35
+
36
+ /// Opens `request.url` and calls back once with `{ url }`, the URL the page
37
+ /// redirected to, or `{ error, message }`, where `error` is `canceled` or
38
+ /// `failed`.
39
+ @objc func start(_ request: [String: Any], callback: @escaping LynxCallbackBlock) {
40
+ // Lynx calls modules off the main thread, and the session presents UI.
41
+ DispatchQueue.main.async {
42
+ self.open(request, callback)
43
+ }
44
+ }
45
+
46
+ private func open(_ request: [String: Any], _ callback: @escaping LynxCallbackBlock) {
47
+ let fail = { (message: String) in callback(["error": "failed", "message": message]) }
48
+ guard session == nil else {
49
+ fail("A sign-in is already open.")
50
+ return
51
+ }
52
+ guard let address = request["url"] as? String, let url = URL(string: address),
53
+ let scheme = request["callbackScheme"] as? String, !scheme.isEmpty
54
+ else {
55
+ fail("The sign-in needs a URL and a callback scheme.")
56
+ return
57
+ }
58
+
59
+ let completion: ASWebAuthenticationSession.CompletionHandler = { [weak self] url, error in
60
+ self?.session = nil
61
+ if let url {
62
+ callback(["url": url.absoluteString])
63
+ } else if let error = error as? ASWebAuthenticationSessionError,
64
+ error.code == .canceledLogin
65
+ {
66
+ callback(["error": "canceled", "message": "The sign-in was canceled."])
67
+ } else {
68
+ fail(error?.localizedDescription ?? "The sign-in page could not be opened.")
69
+ }
70
+ }
71
+ let session: ASWebAuthenticationSession
72
+ if #available(iOS 17.4, *) {
73
+ session = ASWebAuthenticationSession(
74
+ url: url, callback: .customScheme(scheme), completionHandler: completion)
75
+ } else {
76
+ session = ASWebAuthenticationSession(
77
+ url: url, callbackURLScheme: scheme, completionHandler: completion)
78
+ }
79
+ session.presentationContextProvider = self
80
+ session.prefersEphemeralWebBrowserSession = (request["ephemeral"] as? Bool) ?? false
81
+ self.session = session
82
+ if !session.start() {
83
+ self.session = nil
84
+ fail("The sign-in page could not be opened.")
85
+ }
86
+ }
87
+
88
+ /// The sheet opens over the app's window.
89
+ func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
90
+ UIApplication.shared.connectedScenes
91
+ .compactMap { $0 as? UIWindowScene }
92
+ .flatMap(\.windows)
93
+ .first(where: \.isKeyWindow) ?? ASPresentationAnchor()
94
+ }
95
+ }