@blotch/angular-lynx-native 22.3.1 → 22.3.3

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 (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -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/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,284 @@
1
+ import AVFoundation
2
+ import Lynx
3
+ import UIKit
4
+ import Vision
5
+ import VisionKit
6
+
7
+ /// The native module behind the runtime's `LynxBarcodeScanner`, which calls it
8
+ /// as `NativeModules.AngularLynxBarcodeScanner` (from the background thread,
9
+ /// where NativeModules lives).
10
+ ///
11
+ /// It opens VisionKit's DataScannerViewController, the system's own live
12
+ /// scanner, over the app, and closes it at the first code it reads. VisionKit
13
+ /// has it from iOS 16 on phones with an A12 chip or later; anywhere else,
14
+ /// including the Simulator, a scan reports `unavailable`.
15
+ ///
16
+ /// Only an app whose angular.json sets `permissions.camera` has this file: App
17
+ /// Store Connect flags an app whose code uses the camera without
18
+ /// NSCameraUsageDescription (ITMS-90683), which only that permission writes.
19
+ /// So LynxViewController registers it by its Objective-C name, which builds
20
+ /// whether the generator kept it or not, and nothing else may name the class.
21
+ @objc(AngularLynxBarcodeScannerModule)
22
+ final class BarcodeScannerModule: NSObject, LynxModule {
23
+ static var name: String { "AngularLynxBarcodeScanner" }
24
+
25
+ static var methodLookup: [String: String] {
26
+ ["scan": NSStringFromSelector(#selector(scan(_:callback:)))]
27
+ }
28
+
29
+ /// The open scanner, which ends the scan, as an `AnyObject` because its
30
+ /// type exists only from iOS 16.
31
+ private var open: AnyObject?
32
+
33
+ override init() {
34
+ super.init()
35
+ }
36
+
37
+ // Swift can't import an optional initializer as optional, so Lynx's
38
+ // initWithParam: is required here. Registered without a param, the module
39
+ // ignores it.
40
+ init(param: Any) {
41
+ super.init()
42
+ }
43
+
44
+ /// Opens the scanner and calls back once with `{ format, value }`, or
45
+ /// `{ error, message }`, where `error` is `canceled`, `unavailable`,
46
+ /// `denied` or `failed`.
47
+ @objc func scan(_ request: [String: Any], callback: @escaping LynxCallbackBlock) {
48
+ let formats = (request["formats"] as? [String]) ?? []
49
+ // Lynx calls modules off the main thread, and the scanner is UI.
50
+ DispatchQueue.main.async {
51
+ self.start(formats, callback)
52
+ }
53
+ }
54
+
55
+ // VisionKit's scanner and UIKit are main-actor isolated, and Swift checks
56
+ // it: these run on the main queue (see scan).
57
+ @MainActor
58
+ private func start(_ formats: [String], _ callback: @escaping LynxCallbackBlock) {
59
+ guard #available(iOS 16, *) else {
60
+ callback(Self.error("unavailable", "The barcode scanner needs iOS 16 or later."))
61
+ return
62
+ }
63
+ guard open == nil else {
64
+ callback(Self.error("failed", "A scan is already open."))
65
+ return
66
+ }
67
+ // isSupported is the hardware and the OS; isAvailable also says no when
68
+ // the camera's restricted or the person declined it, which is told
69
+ // apart below, after asking.
70
+ guard DataScannerViewController.isSupported else {
71
+ callback(
72
+ Self.error("unavailable", "This device has no barcode scanner. It needs an A12 chip or later."))
73
+ return
74
+ }
75
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
76
+ case .authorized:
77
+ present(formats, callback)
78
+ case .notDetermined:
79
+ // The prompt shows NSCameraUsageDescription, angular.json's
80
+ // permissions.camera.
81
+ AVCaptureDevice.requestAccess(for: .video) { granted in
82
+ DispatchQueue.main.async {
83
+ if granted {
84
+ self.present(formats, callback)
85
+ } else {
86
+ callback(Self.error("denied", "The app isn't allowed to use the camera."))
87
+ }
88
+ }
89
+ }
90
+ default:
91
+ callback(Self.error("denied", "The app isn't allowed to use the camera."))
92
+ }
93
+ }
94
+
95
+ @available(iOS 16, *)
96
+ @MainActor
97
+ private func present(_ formats: [String], _ callback: @escaping LynxCallbackBlock) {
98
+ guard open == nil else {
99
+ callback(Self.error("failed", "A scan is already open."))
100
+ return
101
+ }
102
+ guard DataScannerViewController.isAvailable else {
103
+ callback(Self.error("unavailable", "The camera isn't available right now."))
104
+ return
105
+ }
106
+ guard let presenter = topViewController() else {
107
+ callback(Self.error("failed", "There's no screen to open the scanner over."))
108
+ return
109
+ }
110
+ let symbologies = Self.symbologies(formats)
111
+ // Called once the sheet has gone (ScanSession.finish), so a scan that
112
+ // comes in while it animates away finds this one still open and fails,
113
+ // rather than presenting over it.
114
+ let session = ScanSession(formats: Set(formats)) { [weak self] result in
115
+ self?.open = nil
116
+ callback(result)
117
+ }
118
+ let scanner = DataScannerViewController(
119
+ recognizedDataTypes: [.barcode(symbologies: symbologies)],
120
+ qualityLevel: .balanced,
121
+ recognizesMultipleItems: false,
122
+ isHighFrameRateTrackingEnabled: false,
123
+ isHighlightingEnabled: true)
124
+ scanner.delegate = session
125
+ session.scanner = scanner
126
+ // A navigation bar for the Cancel button, since the scanner has none of
127
+ // its own, in a sheet the person can also swipe down to close.
128
+ scanner.navigationItem.leftBarButtonItem = UIBarButtonItem(
129
+ systemItem: .cancel,
130
+ primaryAction: UIAction { [weak session] _ in session?.cancel() })
131
+ let navigation = UINavigationController(rootViewController: scanner)
132
+ navigation.presentationController?.delegate = session
133
+ open = session
134
+ presenter.present(navigation, animated: true) {
135
+ do {
136
+ try scanner.startScanning()
137
+ } catch {
138
+ session.finish(Self.error("failed", error.localizedDescription))
139
+ }
140
+ }
141
+ }
142
+
143
+ /// The runtime's BarcodeFormat names as Vision's symbologies. VisionKit
144
+ /// reads a UPC-A as an EAN-13 with a leading 0, so `upcA` asks for EAN-13
145
+ /// and ScanSession gives the 12 digits back. ITF covers ITF-14 and
146
+ /// interleaved 2 of 5, as Android's `itf` does.
147
+ @available(iOS 16, *)
148
+ private static func symbologies(_ formats: [String]) -> [VNBarcodeSymbology] {
149
+ let all: [String: [VNBarcodeSymbology]] = [
150
+ "qr": [.qr, .microQR],
151
+ "aztec": [.aztec],
152
+ "dataMatrix": [.dataMatrix],
153
+ "pdf417": [.pdf417, .microPDF417],
154
+ "ean13": [.ean13],
155
+ "ean8": [.ean8],
156
+ "upcA": [.ean13],
157
+ "upcE": [.upce],
158
+ "code39": [.code39, .code39Checksum, .code39FullASCII, .code39FullASCIIChecksum],
159
+ "code93": [.code93, .code93i],
160
+ "code128": [.code128],
161
+ "itf": [.itf14, .i2of5, .i2of5Checksum],
162
+ "codabar": [.codabar],
163
+ ]
164
+ var symbologies: [VNBarcodeSymbology] = []
165
+ for format in formats {
166
+ for symbology in all[format] ?? [] where !symbologies.contains(symbology) {
167
+ symbologies.append(symbology)
168
+ }
169
+ }
170
+ return symbologies
171
+ }
172
+
173
+ static func error(_ code: String, _ message: String) -> [String: Any] {
174
+ ["error": code, "message": message]
175
+ }
176
+
177
+ @MainActor
178
+ private func topViewController() -> UIViewController? {
179
+ let window = UIApplication.shared.connectedScenes
180
+ .compactMap { $0 as? UIWindowScene }
181
+ .flatMap(\.windows)
182
+ .first(where: \.isKeyWindow)
183
+ var top = window?.rootViewController
184
+ while let presented = top?.presentedViewController {
185
+ top = presented
186
+ }
187
+ return top
188
+ }
189
+ }
190
+
191
+ /// One open scanner: it reports the first code read, a cancel or a failure,
192
+ /// once, and closes the sheet.
193
+ @available(iOS 16, *)
194
+ @MainActor
195
+ private final class ScanSession: NSObject, DataScannerViewControllerDelegate,
196
+ UIAdaptivePresentationControllerDelegate
197
+ {
198
+ weak var scanner: DataScannerViewController?
199
+ private let formats: Set<String>
200
+ private var done: (([String: Any]) -> Void)?
201
+
202
+ init(formats: Set<String>, done: @escaping ([String: Any]) -> Void) {
203
+ self.formats = formats
204
+ self.done = done
205
+ }
206
+
207
+ /// Reports `result` once the sheet is gone, which is also when the module
208
+ /// lets the next scan open: UIKit can drop a presentation over a sheet
209
+ /// that's still animating away, without calling its completion, which
210
+ /// would leave that scan open and unanswered for good.
211
+ func finish(_ result: [String: Any], alreadyDismissed: Bool = false) {
212
+ guard let done else { return }
213
+ self.done = nil
214
+ scanner?.stopScanning()
215
+ guard !alreadyDismissed, let sheet = scanner?.navigationController,
216
+ sheet.presentingViewController != nil
217
+ else {
218
+ done(result)
219
+ return
220
+ }
221
+ sheet.dismiss(animated: true) { done(result) }
222
+ }
223
+
224
+ func cancel() {
225
+ finish(BarcodeScannerModule.error("canceled", "The scan was canceled."))
226
+ }
227
+
228
+ func dataScanner(
229
+ _ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem],
230
+ allItems: [RecognizedItem]
231
+ ) {
232
+ for item in addedItems {
233
+ guard case .barcode(let barcode) = item, let value = barcode.payloadStringValue,
234
+ let format = format(of: barcode.observation.symbology, value: value)
235
+ else { continue }
236
+ finish(["format": format.name, "value": format.value])
237
+ return
238
+ }
239
+ }
240
+
241
+ func dataScanner(
242
+ _ dataScanner: DataScannerViewController, becameUnavailableWithError error: DataScannerViewController.ScanningUnavailable
243
+ ) {
244
+ switch error {
245
+ case .cameraRestricted:
246
+ finish(BarcodeScannerModule.error("denied", "The app isn't allowed to use the camera."))
247
+ default:
248
+ finish(BarcodeScannerModule.error("unavailable", "The camera stopped being available."))
249
+ }
250
+ }
251
+
252
+ /// Swiping the sheet down closes it without the Cancel button.
253
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
254
+ finish(
255
+ BarcodeScannerModule.error("canceled", "The scan was canceled."), alreadyDismissed: true)
256
+ }
257
+
258
+ /// The runtime's name for what Vision read, or nil for a kind the app
259
+ /// didn't ask for (an EAN-13 when it only asked for UPC-A, say).
260
+ private func format(of symbology: VNBarcodeSymbology, value: String) -> (name: String, value: String)? {
261
+ let name: String
262
+ switch symbology {
263
+ case .qr, .microQR: name = "qr"
264
+ case .aztec: name = "aztec"
265
+ case .dataMatrix: name = "dataMatrix"
266
+ case .pdf417, .microPDF417: name = "pdf417"
267
+ case .ean13:
268
+ // A UPC-A is an EAN-13 whose first digit is 0.
269
+ if formats.contains("upcA"), value.count == 13, value.hasPrefix("0") {
270
+ return ("upcA", String(value.dropFirst()))
271
+ }
272
+ name = "ean13"
273
+ case .ean8: name = "ean8"
274
+ case .upce: name = "upcE"
275
+ case .code39, .code39Checksum, .code39FullASCII, .code39FullASCIIChecksum: name = "code39"
276
+ case .code93, .code93i: name = "code93"
277
+ case .code128: name = "code128"
278
+ case .itf14, .i2of5, .i2of5Checksum: name = "itf"
279
+ case .codabar: name = "codabar"
280
+ default: return nil
281
+ }
282
+ return formats.contains(name) ? (name, value) : nil
283
+ }
284
+ }
@@ -0,0 +1,256 @@
1
+ import Foundation
2
+ import LocalAuthentication
3
+ import Lynx
4
+ import Security
5
+
6
+ /// The native module behind the runtime's `LynxBiometrics`, and the values
7
+ /// `LynxSecureStorage` keeps behind Face ID or Touch ID (`requireBiometrics`).
8
+ /// The runtime calls it as `NativeModules.AngularLynxBiometrics`, from the
9
+ /// background thread, where NativeModules lives.
10
+ ///
11
+ /// Only an app with `permissions.biometrics` in angular.json has this file:
12
+ /// the generator deletes it from the others, which then have no
13
+ /// NSFaceIDUsageDescription, without which Face ID fails.
14
+ /// LynxViewController registers it by its Objective-C name, so the shell
15
+ /// builds either way.
16
+ ///
17
+ /// A guarded value is a Keychain item of its own service, with access
18
+ /// control `.biometryCurrentSet`: the Keychain hands its data over only after
19
+ /// a face or a finger enrolled now confirms the person, and enrolling a new
20
+ /// one invalidates it. Writing one doesn't prompt. Each method calls back once
21
+ /// with `{}`, `{ value }`, the availability, or `{ error, message }`, where
22
+ /// `error` is one of the runtime's BiometricsErrorCode values.
23
+ @objc(AngularLynxBiometricsModule)
24
+ final class BiometricsModule: NSObject, LynxModule {
25
+ static var name: String { "AngularLynxBiometrics" }
26
+
27
+ static var methodLookup: [String: String] {
28
+ [
29
+ "availability": NSStringFromSelector(#selector(availability(_:))),
30
+ "authenticate": NSStringFromSelector(#selector(authenticate(_:callback:))),
31
+ "getItem": NSStringFromSelector(#selector(getItem(_:reason:callback:))),
32
+ "setItem": NSStringFromSelector(#selector(setItem(_:value:callback:))),
33
+ "removeItem": NSStringFromSelector(#selector(removeItem(_:callback:))),
34
+ "clear": NSStringFromSelector(#selector(clear(_:))),
35
+ ]
36
+ }
37
+
38
+ private let service = "\(Bundle.main.bundleIdentifier ?? "app").angular-lynx.biometric-storage"
39
+
40
+ /// Keychain calls block, and a guarded read waits for the person, so they
41
+ /// run off the JavaScript thread, one at a time and in the order they were
42
+ /// made, as SecureStorageModule's do.
43
+ private static let queue = DispatchQueue(label: "dev.angularlynx.biometric-storage")
44
+
45
+ /// angular.json's `permissions.biometrics`, which a guarded read shows on
46
+ /// Touch ID when the app gives no reason of its own.
47
+ private static var defaultReason: String {
48
+ Bundle.main.object(forInfoDictionaryKey: "NSFaceIDUsageDescription") as? String
49
+ ?? "Confirm it's you"
50
+ }
51
+
52
+ override init() {
53
+ super.init()
54
+ }
55
+
56
+ // Swift can't import an optional initializer as optional, so Lynx's
57
+ // initWithParam: is required here. Registered without a param, the module
58
+ // ignores it.
59
+ init(param: Any) {
60
+ super.init()
61
+ }
62
+
63
+ /// `{ type, enrolled, deviceCredential }`. LAContext reports the sensor's
64
+ /// type once canEvaluatePolicy has run, whatever it returns, so a phone
65
+ /// with Face ID nobody has set up still says `faceID`.
66
+ @objc func availability(_ callback: @escaping LynxCallbackBlock) {
67
+ let context = LAContext()
68
+ var error: NSError?
69
+ let ready = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
70
+ let code = error.map { LAError.Code(rawValue: $0.code) } ?? nil
71
+ // Locked out still means a face or a finger is set up.
72
+ let enrolled = ready || code == .biometryLockout
73
+ let deviceCredential = LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)
74
+ callback([
75
+ "type": Self.typeName(context.biometryType),
76
+ "enrolled": enrolled,
77
+ "deviceCredential": deviceCredential,
78
+ ])
79
+ }
80
+
81
+ /// Shows Face ID or Touch ID with `{ reason, allowDeviceCredential,
82
+ /// cancelLabel }`, and calls back with `{}` once the person is confirmed.
83
+ @objc func authenticate(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
84
+ let reason = options["reason"] as? String ?? Self.defaultReason
85
+ let allowDeviceCredential = options["allowDeviceCredential"] as? Bool ?? false
86
+ let context = LAContext()
87
+ if let cancel = options["cancelLabel"] as? String {
88
+ context.localizedCancelTitle = cancel
89
+ }
90
+ // Without the passcode, iOS's "Enter Password" button after a failed
91
+ // try would end the prompt with nothing the app can do: hide it.
92
+ if !allowDeviceCredential {
93
+ context.localizedFallbackTitle = ""
94
+ }
95
+ let policy: LAPolicy =
96
+ allowDeviceCredential ? .deviceOwnerAuthentication : .deviceOwnerAuthenticationWithBiometrics
97
+ var error: NSError?
98
+ guard context.canEvaluatePolicy(policy, error: &error) else {
99
+ callback(Self.failure(error))
100
+ return
101
+ }
102
+ context.evaluatePolicy(policy, localizedReason: reason) { success, error in
103
+ callback(success ? [:] : Self.failure(error as NSError?))
104
+ }
105
+ }
106
+
107
+ /// The value stored under `key`, once the person confirms, as `{ value }`,
108
+ /// or `{}` without prompting when there's none.
109
+ @objc func getItem(_ key: String, reason: String, callback: @escaping LynxCallbackBlock) {
110
+ Self.queue.async {
111
+ // Whether there's one, from its attributes, which the Keychain gives
112
+ // without asking: a missing key mustn't show a prompt.
113
+ var probe = self.query(key)
114
+ probe[kSecReturnAttributes as String] = true
115
+ let context = LAContext()
116
+ context.interactionNotAllowed = true
117
+ probe[kSecUseAuthenticationContext as String] = context
118
+ var found: AnyObject?
119
+ let exists = SecItemCopyMatching(probe as CFDictionary, &found)
120
+ guard exists == errSecSuccess || exists == errSecInteractionNotAllowed else {
121
+ callback(exists == errSecItemNotFound ? [:] : Self.keychainFailure(exists))
122
+ return
123
+ }
124
+
125
+ let prompt = LAContext()
126
+ prompt.localizedReason = reason.isEmpty ? Self.defaultReason : reason
127
+ prompt.localizedFallbackTitle = ""
128
+ var query = self.query(key)
129
+ query[kSecReturnData as String] = true
130
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
131
+ query[kSecUseAuthenticationContext as String] = prompt
132
+ var data: AnyObject?
133
+ let status = SecItemCopyMatching(query as CFDictionary, &data)
134
+ if status == errSecSuccess, let data = data as? Data,
135
+ let value = String(data: data, encoding: .utf8)
136
+ {
137
+ callback(["value": value])
138
+ } else if status == errSecItemNotFound {
139
+ // Invalidated by a newly enrolled face or finger.
140
+ callback([:])
141
+ } else {
142
+ callback(Self.keychainFailure(status))
143
+ }
144
+ }
145
+ }
146
+
147
+ /// Stores `value` under `key`, behind the faces and fingers enrolled now,
148
+ /// in place of what was there. Doesn't prompt.
149
+ @objc func setItem(_ key: String, value: String, callback: @escaping LynxCallbackBlock) {
150
+ Self.queue.async {
151
+ // A value only a face or a finger enrolled now opens needs one, and a
152
+ // passcode: report why not as the runtime's codes, which an app falls
153
+ // back on, rather than the Keychain's error. Locked out still has one.
154
+ var unready: NSError?
155
+ if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &unready),
156
+ unready.flatMap({ LAError.Code(rawValue: $0.code) }) != .biometryLockout
157
+ {
158
+ callback(Self.failure(unready))
159
+ return
160
+ }
161
+ var error: Unmanaged<CFError>?
162
+ // WhenPasscodeSet: biometrics need a passcode, and the item goes with
163
+ // it, never leaving the device.
164
+ guard
165
+ let access = SecAccessControlCreateWithFlags(
166
+ nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, .biometryCurrentSet, &error)
167
+ else {
168
+ callback([
169
+ "error": "failed",
170
+ "message": error?.takeRetainedValue().localizedDescription ?? "No access control.",
171
+ ])
172
+ return
173
+ }
174
+ // Updating a guarded item's data would itself ask, so it's replaced.
175
+ SecItemDelete(self.query(key) as CFDictionary)
176
+ var item = self.query(key)
177
+ item[kSecValueData as String] = Data(value.utf8)
178
+ item[kSecAttrAccessControl as String] = access
179
+ let status = SecItemAdd(item as CFDictionary, nil)
180
+ callback(status == errSecSuccess ? [:] : Self.keychainFailure(status))
181
+ }
182
+ }
183
+
184
+ @objc func removeItem(_ key: String, callback: @escaping LynxCallbackBlock) {
185
+ Self.queue.async {
186
+ self.delete(self.query(key), callback)
187
+ }
188
+ }
189
+
190
+ @objc func clear(_ callback: @escaping LynxCallbackBlock) {
191
+ Self.queue.async {
192
+ self.delete(
193
+ [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: self.service],
194
+ callback)
195
+ }
196
+ }
197
+
198
+ private func query(_ key: String) -> [String: Any] {
199
+ [
200
+ kSecClass as String: kSecClassGenericPassword,
201
+ kSecAttrService as String: service,
202
+ kSecAttrAccount as String: key,
203
+ ]
204
+ }
205
+
206
+ private func delete(_ query: [String: Any], _ callback: LynxCallbackBlock) {
207
+ let status = SecItemDelete(query as CFDictionary)
208
+ callback(
209
+ status == errSecSuccess || status == errSecItemNotFound ? [:] : Self.keychainFailure(status))
210
+ }
211
+
212
+ private static func typeName(_ type: LABiometryType) -> String {
213
+ switch type {
214
+ case .faceID: return "faceID"
215
+ case .touchID: return "touchID"
216
+ case .none: return "none"
217
+ default:
218
+ // .opticID arrived in iOS 17, after the shell's deployment target.
219
+ if #available(iOS 17.0, *), type == .opticID { return "opticID" }
220
+ return "none"
221
+ }
222
+ }
223
+
224
+ /// An LAError as the runtime's error codes.
225
+ private static func failure(_ error: NSError?) -> [String: Any] {
226
+ let message = error?.localizedDescription ?? "The person couldn't be confirmed."
227
+ let code: String
228
+ switch error.flatMap({ LAError.Code(rawValue: $0.code) }) {
229
+ case .userCancel?, .systemCancel?, .appCancel?, .userFallback?:
230
+ code = "canceled"
231
+ case .biometryLockout?:
232
+ code = "lockout"
233
+ case .biometryNotEnrolled?:
234
+ code = "notEnrolled"
235
+ case .biometryNotAvailable?, .passcodeNotSet?:
236
+ code = "unavailable"
237
+ default:
238
+ code = "failed"
239
+ }
240
+ return ["error": code, "message": message]
241
+ }
242
+
243
+ /// A Keychain status as the runtime's error codes: a guarded read reports
244
+ /// the prompt's outcome this way.
245
+ private static func keychainFailure(_ status: OSStatus) -> [String: Any] {
246
+ let message = SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)"
247
+ switch status {
248
+ case errSecUserCanceled:
249
+ return ["error": "canceled", "message": message]
250
+ case errSecNotAvailable, errSecInteractionNotAllowed:
251
+ return ["error": "unavailable", "message": message]
252
+ default:
253
+ return ["error": "failed", "message": message]
254
+ }
255
+ }
256
+ }