@capgo/capacitor-updater 8.52.1-beta.pr937.1951.1 → 8.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -2
  2. package/Package.swift +0 -5
  3. package/README.md +199 -67
  4. package/android/build.gradle +9 -88
  5. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +60 -32
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +246 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +45 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +5539 -1066
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +3754 -494
  11. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +496 -0
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +56 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +14 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +6 -23
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1541 -0
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +258 -0
  19. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +45 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +1 -6
  22. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +417 -217
  24. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +1 -3
  25. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  26. package/dist/docs.json +379 -28
  27. package/dist/esm/definitions.d.ts +209 -10
  28. package/dist/esm/definitions.js.map +1 -1
  29. package/dist/plugin.cjs.js.map +1 -1
  30. package/dist/plugin.js.map +1 -1
  31. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  32. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  33. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  34. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  35. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5247 -199
  36. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  37. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +3878 -365
  38. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +328 -0
  39. package/ios/Sources/CapacitorUpdaterPlugin/DelayCondition.swift +74 -0
  40. package/ios/Sources/CapacitorUpdaterPlugin/DelayUntilNext.swift +30 -0
  41. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  42. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +471 -0
  43. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  44. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  45. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  46. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +221 -63
  47. package/ios/Sources/CapacitorUpdaterPlugin/UserDefaultsExtension.swift +46 -0
  48. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +147 -5
  49. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  50. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  51. package/package.json +15 -19
  52. package/android/consumer-rules.pro +0 -15
  53. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCore.java +0 -67
  54. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCoreNative.java +0 -97
  55. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoDownloadWorker.java +0 -188
  56. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngine.java +0 -114
  57. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHolder.java +0 -59
  58. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHost.java +0 -118
  59. package/android/src/main/java/ee/forgr/capacitor_updater/EngineMethodLanes.java +0 -168
  60. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+AppStore.swift +0 -171
  61. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Methods.swift +0 -168
  62. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Overlays.swift +0 -285
  63. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+WebView.swift +0 -134
  64. package/ios/Sources/CapacitorUpdaterPlugin/CapgoCore.swift +0 -61
  65. package/ios/Sources/CapacitorUpdaterPlugin/CapgoEngine.swift +0 -319
@@ -1,134 +0,0 @@
1
- /*
2
- * This Source Code Form is subject to the terms of the Mozilla Public
3
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
- */
6
-
7
- import Foundation
8
- import Capacitor
9
- import UIKit
10
- import WebKit
11
-
12
- /// WebView side of the engine hooks: serving a bundle, stamping the page
13
- /// generation for `notifyAppReady`, the keep-URL-path flag and the preview notice.
14
- extension CapacitorUpdaterPlugin {
15
- var builtinFolder: URL {
16
- (Bundle.main.resourceURL ?? Bundle.main.bundleURL).appendingPathComponent("public")
17
- }
18
-
19
- /// Folder served for the engine's current bundle path. The id is re-resolved
20
- /// under the bundle root: the app container path changes across installs.
21
- func bundleFolder(path: String, isBuiltin: Bool) -> URL {
22
- if isBuiltin || path.isEmpty {
23
- return builtinFolder
24
- }
25
- let id = URL(fileURLWithPath: path).lastPathComponent
26
- return (try? implementation.bundleDirectory(id: id)) ?? builtinFolder
27
- }
28
-
29
- func initialLoad(_ loaded: [String: Any]) -> Bool {
30
- guard let bridge = self.bridge else { return false }
31
- let id = (loaded["bundle"] as? [String: Any])?["id"] as? String ?? "builtin"
32
- var dest = bundleFolder(path: loaded["path"] as? String ?? "", isBuiltin: loaded["isBuiltin"] as? Bool ?? true)
33
- if !FileManager.default.fileExists(atPath: dest.path) {
34
- logger.error("Initial load fail - file at path \(dest.path) doesn't exist. Defaulting to buildin!! \(id)")
35
- dest = builtinFolder
36
- }
37
- logger.info("Initial load \(id)")
38
- // The view controller does not work during the initial load state.
39
- bridge.setServerBasePath(dest.path)
40
- return true
41
- }
42
-
43
- /// `applyBundle` hook: stamps the page generation and points the WebView at the bundle.
44
- func applyBundle(_ payload: [String: Any]) -> [String: Any] {
45
- guard let viewController = self.bridge?.viewController as? CAPBridgeViewController else {
46
- logger.error("Cannot get viewController")
47
- return ["ok": false]
48
- }
49
- guard let capBridge = viewController.bridge else {
50
- logger.error("Cannot get capBridge")
51
- return ["ok": false]
52
- }
53
- let guarded = stampReadyGeneration(payload["readyScript"] as? String ?? "", webView: viewController.webView)
54
- let dest = bundleFolder(path: payload["path"] as? String ?? "", isBuiltin: payload["isBuiltin"] as? Bool ?? false)
55
- if keepUrlPathAfterReload {
56
- if let currentURL = viewController.webView?.url {
57
- capBridge.setServerBasePath(dest.path)
58
- var urlComponents = URLComponents(url: capBridge.config.serverURL, resolvingAgainstBaseURL: false)
59
- urlComponents?.path = currentURL.path
60
- urlComponents?.query = currentURL.query
61
- urlComponents?.fragment = currentURL.fragment
62
- if let finalUrl = urlComponents?.url {
63
- _ = viewController.webView?.load(URLRequest(url: finalUrl))
64
- } else {
65
- logger.error("Unable to build final URL when keeping path after reload; falling back to base path")
66
- viewController.setServerBasePath(path: dest.path)
67
- }
68
- } else {
69
- logger.error("vc.webView?.url is null? Falling back to base path reload.")
70
- viewController.setServerBasePath(path: dest.path)
71
- }
72
- } else {
73
- viewController.setServerBasePath(path: dest.path)
74
- }
75
- return ["ok": true, "guard": guarded]
76
- }
77
-
78
- /// Makes the next document report its generation with notifyAppReady (`script` is the
79
- /// engine's `readyScript`); false without a webview or a script.
80
- func stampReadyGeneration(_ script: String, webView: WKWebView?) -> Bool {
81
- guard let webView else {
82
- logger.warn("Cannot stamp notifyAppReady generation without a webview")
83
- return false
84
- }
85
- guard !script.isEmpty else {
86
- return false
87
- }
88
- let userScript = WKUserScript(
89
- source: script,
90
- injectionTime: .atDocumentStart,
91
- forMainFrameOnly: true
92
- )
93
- webView.configuration.userContentController.addUserScript(userScript)
94
- return true
95
- }
96
-
97
- func syncKeepUrlPathFlag(enabled: Bool) {
98
- let script: String
99
- if enabled {
100
- script = "(function(){ try { localStorage.setItem('\(keepUrlPathFlagKey)', '1'); } catch (err) {} window.__capgoKeepUrlPathAfterReload = true; var evt; try { evt = new CustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', { detail: { enabled: true } }); } catch (e) { evt = document.createEvent('CustomEvent'); evt.initCustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', false, false, { enabled: true }); } window.dispatchEvent(evt); })();"
101
- } else {
102
- script = "(function(){ try { localStorage.removeItem('\(keepUrlPathFlagKey)'); } catch (err) {} delete window.__capgoKeepUrlPathAfterReload; var evt; try { evt = new CustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', { detail: { enabled: false } }); } catch (e) { evt = document.createEvent('CustomEvent'); evt.initCustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', false, false, { enabled: false }); } window.dispatchEvent(evt); })();"
103
- }
104
- DispatchQueue.main.async { [weak self] in
105
- guard let self = self, let webView = self.bridge?.webView else {
106
- return
107
- }
108
- if self.keepUrlPathFlagLastValue != enabled {
109
- let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
110
- webView.configuration.userContentController.addUserScript(userScript)
111
- self.keepUrlPathFlagLastValue = enabled
112
- }
113
- webView.evaluateJavaScript(script, completionHandler: nil)
114
- }
115
- }
116
-
117
- // MARK: - Preview notice
118
-
119
- /// "Preview started" alert; false when it cannot be shown now (the engine retries later).
120
- func showPreviewNotice(gesture: String) -> Bool {
121
- guard let topVC = UIApplication.topViewController(self.bridge?.viewController),
122
- !topVC.isKind(of: UIAlertController.self) else {
123
- return false
124
- }
125
- let alert = UIAlertController(
126
- title: "Preview started",
127
- message: gesture == Self.shakeMenuGestureThreeFingerPinch ? "Three-finger pinch to open menu." : "Shake to open menu.",
128
- preferredStyle: .alert
129
- )
130
- alert.addAction(UIAlertAction(title: "Got it", style: .default))
131
- topVC.present(alert, animated: true)
132
- return true
133
- }
134
- }
@@ -1,61 +0,0 @@
1
- /*
2
- * This Source Code Form is subject to the terms of the Mozilla Public
3
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
- */
6
-
7
- import Foundation
8
- import CapgoUpdaterCore
9
-
10
- /// Swift binding for the shared Rust updater core (`core/`).
11
- ///
12
- /// Every call is `operation name + JSON object in -> JSON object out`, the
13
- /// same surface the Android plugin uses through JNI (`resolvePathInside`).
14
- enum CapgoCore {
15
- struct Failure: Error, CustomStringConvertible {
16
- let code: String
17
- let message: String
18
-
19
- var description: String {
20
- "\(code): \(message)"
21
- }
22
- }
23
-
24
- /// JSON text for `object`, or nil when it is not valid JSON. JSONSerialization raises an
25
- /// Objective-C exception (which Swift cannot catch: the app crashes) on NaN, infinity or a
26
- /// non-JSON type, so it is checked first. Inside an engine callback that would abort.
27
- static func jsonString(_ object: Any) -> String? {
28
- guard JSONSerialization.isValidJSONObject(object),
29
- let data = try? JSONSerialization.data(withJSONObject: object) else {
30
- return nil
31
- }
32
- return String(bytes: data, encoding: .utf8)
33
- }
34
-
35
- /// Runs a core operation. `nil` input values are sent as JSON `null`.
36
- static func call(_ operation: String, _ input: [String: Any?] = [:]) throws -> [String: Any] {
37
- let payload = input.mapValues { $0 ?? NSNull() }
38
- guard let inputJson = jsonString(payload) else {
39
- throw Failure(code: "invalid_input", message: "Input is not a JSON object")
40
- }
41
-
42
- guard let raw = capgo_core_call(operation, inputJson) else {
43
- throw Failure(code: "internal", message: "Core returned no result")
44
- }
45
- defer {
46
- capgo_core_free(raw)
47
- }
48
- let output = Data(bytes: raw, count: strlen(raw))
49
- guard let envelope = try JSONSerialization.jsonObject(with: output) as? [String: Any] else {
50
- throw Failure(code: "internal", message: "Core returned invalid JSON")
51
- }
52
- if envelope["ok"] as? Bool == true {
53
- return envelope["value"] as? [String: Any] ?? [:]
54
- }
55
- let error = envelope["error"] as? [String: Any]
56
- throw Failure(
57
- code: error?["code"] as? String ?? "internal",
58
- message: error?["message"] as? String ?? "Unknown core error"
59
- )
60
- }
61
- }
@@ -1,319 +0,0 @@
1
- /*
2
- * This Source Code Form is subject to the terms of the Mozilla Public
3
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
- */
6
-
7
- import CommonCrypto
8
- import Foundation
9
- import Security
10
- import CapgoUpdaterCore
11
-
12
- /// Platform services the Rust engine calls back into, from any thread.
13
- protocol CapgoEngineHost: AnyObject {
14
- func engineLog(level: Int32, message: String)
15
- func engineKvGet(_ key: String) -> String?
16
- func engineKvSet(_ key: String, _ value: String?)
17
- func engineKvKeys() -> [String]
18
- func engineEmit(_ event: String, _ payload: [String: Any])
19
- /// Platform hook (`applyBundle`, `splash`, `backgroundTask`, ...); nil keeps the engine default.
20
- func engineHook(_ name: String, _ payload: [String: Any]) -> [String: Any]?
21
- }
22
-
23
- /// Swift handle on a Rust updater engine (`core/src/engine`). Thread-safe.
24
- final class CapgoEngine {
25
- private let handle: OpaquePointer
26
-
27
- /// Boxes the host for the C callbacks; weak so the engine never keeps the updater alive.
28
- private final class HostBox {
29
- weak var host: CapgoEngineHost?
30
- init(_ host: CapgoEngineHost) {
31
- self.host = host
32
- }
33
- }
34
-
35
- init?(config: [String: Any], host: CapgoEngineHost) {
36
- guard let configJson = CapgoCore.jsonString(config) else {
37
- return nil
38
- }
39
- let context = Unmanaged.passRetained(HostBox(host)).toOpaque()
40
- let callbacks = CapgoHostCallbacks(
41
- context: context,
42
- log: { context, level, message in
43
- guard let context, let message else { return }
44
- CapgoEngine.box(context).host?.engineLog(level: level, message: String(cString: message))
45
- },
46
- kv_get: { context, key in
47
- guard let context, let key,
48
- let value = CapgoEngine.box(context).host?.engineKvGet(String(cString: key)) else {
49
- return nil
50
- }
51
- return strdup(value)
52
- },
53
- kv_set: { context, key, value in
54
- guard let context, let key else { return }
55
- CapgoEngine.box(context).host?.engineKvSet(String(cString: key), value.map { String(cString: $0) })
56
- },
57
- kv_keys: { context in
58
- guard let context,
59
- let keys = CapgoEngine.box(context).host?.engineKvKeys(),
60
- let json = CapgoCore.jsonString(keys) else {
61
- return nil
62
- }
63
- return strdup(json)
64
- },
65
- emit: { context, event, payload in
66
- guard let context, let event, let payload else { return }
67
- let data = Data(bytes: payload, count: strlen(payload))
68
- let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
69
- CapgoEngine.box(context).host?.engineEmit(String(cString: event), object)
70
- },
71
- free_string: { _, value in
72
- free(value)
73
- },
74
- hook: { context, name, payload in
75
- guard let context, let name else { return nil }
76
- let object = payload.flatMap { raw in
77
- (try? JSONSerialization.jsonObject(with: Data(bytes: raw, count: strlen(raw)))) as? [String: Any]
78
- } ?? [:]
79
- guard let reply = CapgoEngine.box(context).host?.engineHook(String(cString: name), object),
80
- let json = CapgoCore.jsonString(reply) else {
81
- return nil
82
- }
83
- return strdup(json)
84
- },
85
- release: { context in
86
- guard let context else { return }
87
- Unmanaged<HostBox>.fromOpaque(context).release()
88
- },
89
- verify_server_certificate: CapgoEngine.verifyServerCertificateCallback
90
- )
91
- guard let handle = capgo_engine_new(configJson, callbacks) else {
92
- return nil
93
- }
94
- self.handle = handle
95
- }
96
-
97
- deinit {
98
- capgo_engine_free(handle)
99
- }
100
-
101
- typealias VerifyServerCertificateCallback = @convention(c) (
102
- UnsafeMutableRawPointer?,
103
- UnsafePointer<CChar>?,
104
- UnsafePointer<UnsafePointer<UInt8>?>?,
105
- UnsafePointer<Int>?,
106
- Int,
107
- UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?
108
- ) -> Int32
109
-
110
- /// `verify_server_certificate` host callback: 1 when the system trust store accepts the
111
- /// DER chain (leaf first) for the server name; otherwise 0 and the reason in `error`.
112
- static let verifyServerCertificateCallback: VerifyServerCertificateCallback = { _, serverName, certificates, lengths, count, error in
113
- guard let serverName, let certificates, let lengths, count > 0 else {
114
- error?.pointee = strdup("Empty certificate chain")
115
- return 0
116
- }
117
- var chain: [Data] = []
118
- for index in 0..<count {
119
- guard let certificate = certificates[index], lengths[index] > 0 else {
120
- error?.pointee = strdup("Invalid certificate in chain")
121
- return 0
122
- }
123
- chain.append(Data(bytes: certificate, count: lengths[index]))
124
- }
125
- if let reason = verifyServerCertificate(chain: chain, serverName: String(cString: serverName)) {
126
- error?.pointee = strdup(reason)
127
- return 0
128
- }
129
- return 1
130
- }
131
-
132
- /// Evaluates a TLS server chain (DER, leaf first) like URLSession's default handling:
133
- /// `SecTrust` with the SSL policy for `serverName` against the system trust store
134
- /// (including user-installed and MDM roots). Returns nil when trusted, else the reason.
135
- /// `date` overrides the evaluation time (tests only).
136
- static func verifyServerCertificate(
137
- chain: [Data],
138
- serverName: String,
139
- date: Date? = nil,
140
- pinnedDomains: [String: Any]? = pinnedDomainsFromInfoPlist()
141
- ) -> String? {
142
- var certificates: [SecCertificate] = []
143
- for der in chain {
144
- guard let certificate = SecCertificateCreateWithData(nil, der as CFData) else {
145
- return "Invalid certificate in chain"
146
- }
147
- certificates.append(certificate)
148
- }
149
- guard !certificates.isEmpty else {
150
- return "Empty certificate chain"
151
- }
152
- var trust: SecTrust?
153
- let policy = SecPolicyCreateSSL(true, serverName as CFString)
154
- guard SecTrustCreateWithCertificates(certificates as CFArray, policy, &trust) == errSecSuccess, let trust else {
155
- return "Cannot evaluate the certificate chain"
156
- }
157
- if let date, SecTrustSetVerifyDate(trust, date as CFDate) != errSecSuccess {
158
- return "Cannot set the evaluation date"
159
- }
160
- var failure: CFError?
161
- guard SecTrustEvaluateWithError(trust, &failure) else {
162
- return failure.map { ($0 as Error).localizedDescription } ?? "Certificate not trusted"
163
- }
164
- let evaluated = (SecTrustCopyCertificateChain(trust) as? [SecCertificate]) ?? certificates
165
- return pinningFailure(
166
- chain: evaluated.map { SecCertificateCopyData($0) as Data },
167
- serverName: serverName,
168
- pinnedDomains: pinnedDomains
169
- )
170
- }
171
-
172
- // MARK: - ATS certificate pinning (NSPinnedDomains)
173
-
174
- static func pinnedDomainsFromInfoPlist() -> [String: Any]? {
175
- let ats = Bundle.main.infoDictionary?["NSAppTransportSecurity"] as? [String: Any]
176
- return ats?["NSPinnedDomains"] as? [String: Any]
177
- }
178
-
179
- /// URLSession enforces the app's `NSPinnedDomains`; the engine's client is not URLSession, so
180
- /// apply the same rule: for a pinned host, the leaf must match one of `NSPinnedLeafIdentities`
181
- /// and a CA certificate of the evaluated chain one of `NSPinnedCAIdentities` (each list that is
182
- /// present), by the base64 SHA-256 of the certificate's SubjectPublicKeyInfo. The most specific
183
- /// matching domain applies. Returns nil when allowed, else the reason.
184
- static func pinningFailure(chain: [Data], serverName: String, pinnedDomains: [String: Any]?) -> String? {
185
- guard let pinnedDomains, !pinnedDomains.isEmpty else {
186
- return nil
187
- }
188
- let host = serverName.lowercased()
189
- let match = pinnedDomains
190
- .compactMap { domain, value -> (domain: String, settings: [String: Any])? in
191
- guard let settings = value as? [String: Any] else {
192
- return nil
193
- }
194
- return (domain.lowercased(), settings)
195
- }
196
- .filter { entry in
197
- host == entry.domain
198
- || (entry.settings["NSIncludesSubdomains"] as? Bool == true && host.hasSuffix("." + entry.domain))
199
- }
200
- .max { $0.domain.count < $1.domain.count }
201
- guard let settings = match?.settings else {
202
- return nil
203
- }
204
- func pins(_ key: String) -> Set<String>? {
205
- guard let value = settings[key] else {
206
- return nil
207
- }
208
- // A present but malformed list pins to nothing (fails closed) instead of disabling the check.
209
- let identities = value as? [[String: Any]] ?? []
210
- return Set(identities.compactMap { $0["SPKI-SHA256-BASE64"] as? String })
211
- }
212
- let hashes = chain.map { spkiSha256Base64(certificate: $0) }
213
- if let leafPins = pins("NSPinnedLeafIdentities") {
214
- guard let leaf = hashes.first, let leafHash = leaf, leafPins.contains(leafHash) else {
215
- return "Certificate does not match the pinned leaf identities for \(host)"
216
- }
217
- }
218
- if let caPins = pins("NSPinnedCAIdentities") {
219
- guard hashes.dropFirst().contains(where: { $0.map(caPins.contains) ?? false }) else {
220
- return "Certificate does not match the pinned CA identities for \(host)"
221
- }
222
- }
223
- return nil
224
- }
225
-
226
- /// Base64 SHA-256 of the DER SubjectPublicKeyInfo of an X.509 certificate.
227
- static func spkiSha256Base64(certificate der: Data) -> String? {
228
- let bytes = [UInt8](der)
229
- // Certificate ::= SEQUENCE { tbsCertificate SEQUENCE { [0] version OPTIONAL, serialNumber,
230
- // signature, issuer, validity, subject, subjectPublicKeyInfo, ... } ... }
231
- guard let certificate = derElement(bytes, at: 0), bytes[0] == 0x30,
232
- let tbs = derElement(bytes, at: certificate.contentStart), bytes[certificate.contentStart] == 0x30 else {
233
- return nil
234
- }
235
- var offset = tbs.contentStart
236
- if bytes.indices.contains(offset), bytes[offset] == 0xA0, let version = derElement(bytes, at: offset) {
237
- offset = version.end
238
- }
239
- // serialNumber, signature, issuer, validity, subject
240
- for _ in 0..<5 {
241
- guard let element = derElement(bytes, at: offset) else {
242
- return nil
243
- }
244
- offset = element.end
245
- }
246
- guard bytes.indices.contains(offset), bytes[offset] == 0x30, let spki = derElement(bytes, at: offset),
247
- spki.end <= tbs.end else {
248
- return nil
249
- }
250
- var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
251
- let slice = Array(bytes[offset..<spki.end])
252
- _ = CC_SHA256(slice, CC_LONG(slice.count), &digest)
253
- return Data(digest).base64EncodedString()
254
- }
255
-
256
- /// One DER TLV at `offset`: where its content starts and where it ends.
257
- private static func derElement(_ bytes: [UInt8], at offset: Int) -> (contentStart: Int, end: Int)? {
258
- guard offset + 1 < bytes.count else {
259
- return nil
260
- }
261
- var index = offset + 1
262
- var length = Int(bytes[index])
263
- index += 1
264
- if length & 0x80 != 0 {
265
- let count = length & 0x7F
266
- guard count > 0, count <= 4, index + count <= bytes.count else {
267
- return nil
268
- }
269
- length = 0
270
- for _ in 0..<count {
271
- length = (length << 8) | Int(bytes[index])
272
- index += 1
273
- }
274
- }
275
- let end = index + length
276
- guard end <= bytes.count else {
277
- return nil
278
- }
279
- return (index, end)
280
- }
281
-
282
- private static func box(_ context: UnsafeMutableRawPointer) -> HostBox {
283
- Unmanaged<HostBox>.fromOpaque(context).takeUnretainedValue()
284
- }
285
-
286
- /// Runs an engine operation (blocking). Returns the JSON value (object, array or NSNull).
287
- func callValue(_ operation: String, _ input: [String: Any?] = [:]) throws -> Any {
288
- let payload = input.mapValues { $0 ?? NSNull() }
289
- guard let inputJson = CapgoCore.jsonString(payload) else {
290
- throw CapgoCore.Failure(code: "invalid_input", message: "Input is not a JSON object")
291
- }
292
- // Keep this wrapper alive for the whole native call: its deinit frees the engine.
293
- let result: UnsafeMutablePointer<CChar>? = withExtendedLifetime(self) {
294
- capgo_engine_call(handle, operation, inputJson)
295
- }
296
- guard let raw = result else {
297
- throw CapgoCore.Failure(code: "internal", message: "Engine returned no result")
298
- }
299
- defer {
300
- capgo_core_free(raw)
301
- }
302
- let output = Data(bytes: raw, count: strlen(raw))
303
- guard let envelope = try JSONSerialization.jsonObject(with: output, options: [.fragmentsAllowed]) as? [String: Any] else {
304
- throw CapgoCore.Failure(code: "internal", message: "Engine returned invalid JSON")
305
- }
306
- if envelope["ok"] as? Bool == true {
307
- return envelope["value"] ?? NSNull()
308
- }
309
- let error = envelope["error"] as? [String: Any]
310
- throw CapgoCore.Failure(
311
- code: error?["code"] as? String ?? "internal",
312
- message: error?["message"] as? String ?? "Unknown engine error"
313
- )
314
- }
315
-
316
- func call(_ operation: String, _ input: [String: Any?] = [:]) throws -> [String: Any] {
317
- try callValue(operation, input) as? [String: Any] ?? [:]
318
- }
319
- }