@blotch/angular-lynx-native 22.2.6 → 22.2.8

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,7 +19,7 @@ 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. Android also has `AngularLynxShell`, for the back button.
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
23
 
24
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`).
25
25
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotch/angular-lynx-native",
3
- "version": "22.2.6",
3
+ "version": "22.2.8",
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": {
@@ -38,6 +38,15 @@ Back is off by default, so it leaves the app like any root screen. The runtime t
38
38
 
39
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
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
+
41
50
  ## Global props
42
51
 
43
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.
@@ -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
+ }
@@ -82,6 +82,8 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
82
82
  setGenericResourceFetcher(AssetGenericResourceFetcher(this@MainActivity))
83
83
  registerModule(ShellModule.NAME, ShellModule::class.java, this@MainActivity)
84
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)
85
87
  // Lynx's core has no <input>, <overlay>, <svg>, <blur-view> etc.;
86
88
  // these come from XElement (see app/build.gradle.kts). Lynx
87
89
  // Explorer registers them the same way.
@@ -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,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
+ }
@@ -16,6 +16,8 @@ final class LynxViewController: UIViewController {
16
16
  // The shell's native modules, which the runtime's services call.
17
17
  let config = LynxConfig(provider: LynxEnv.sharedInstance().config.templateProvider)
18
18
  config.register(WebAuthModule.self)
19
+ config.register(LocalStorageModule.self)
20
+ config.register(SecureStorageModule.self)
19
21
  let lynxView = LynxView { builder in
20
22
  builder.config = config
21
23
  builder.screenSize = screenSize
@@ -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
+ }