@capgo/capacitor-updater 8.54.2 → 9.0.1
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/CapgoCapacitorUpdater.podspec +2 -2
- package/Package.swift +3 -4
- package/README.md +162 -417
- package/android/build.gradle +7 -7
- package/android/consumer-rules.pro +48 -0
- package/android/proguard-rules.pro +1 -23
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1420 -404
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1100 -308
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +102 -65
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +155 -18
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +22 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +82 -21
- package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
- package/dist/docs.json +44 -566
- package/dist/esm/definitions.d.ts +97 -215
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +197 -84
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +402 -139
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +81 -55
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +24 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +2 -1
- package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
- package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
- package/package.json +15 -13
|
@@ -31,38 +31,51 @@ public struct CryptoCipher {
|
|
|
31
31
|
return str.unicodeScalars.allSatisfy { hexCharacterSet.contains($0) }
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
/// Plaintext and ciphertext SHA-256 digests recovered from a signed bundle checksum, as lowercase hex.
|
|
35
|
+
public struct BundleChecksum {
|
|
36
|
+
/// SHA-256 of the decrypted bundle or file, compared after decryption.
|
|
37
|
+
public let plain: String
|
|
38
|
+
/// SHA-256 of the encrypted bytes as served, checked before decryption. `nil` without a public key.
|
|
39
|
+
public let ciphertext: String?
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// Size of the signed checksum payload: SHA-256 of the plaintext followed by SHA-256 of the ciphertext.
|
|
43
|
+
static let signedChecksumPayloadBytes = 64
|
|
44
|
+
|
|
45
|
+
/// Thrown when encrypted bytes do not match the signed ciphertext checksum. Nothing was decrypted.
|
|
46
|
+
enum CiphertextChecksumError: Error, LocalizedError {
|
|
47
|
+
case missing
|
|
48
|
+
case mismatch
|
|
49
|
+
|
|
50
|
+
var errorDescription: String? {
|
|
51
|
+
switch self {
|
|
52
|
+
case .missing:
|
|
53
|
+
return "Encrypted bundle has no signed ciphertext checksum. Re-upload the bundle with a current Capgo CLI."
|
|
54
|
+
case .mismatch:
|
|
55
|
+
return "Checksum verification failed: encrypted bytes do not match the signed checksum"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// Decrypts the RSA encrypted bundle checksum. Since 9.0.0 the signed payload is 64 bytes: the SHA-256 of the
|
|
61
|
+
/// plaintext followed by the SHA-256 of the encrypted bytes (Capgo CLI "V4" checksum). Returns `checksum` as the
|
|
62
|
+
/// plain digest when no public key is configured. Throws for anything that is not an even-length hex string of
|
|
63
|
+
/// 256 bytes signed with the matching private key, and for the 32-byte payload of older CLIs.
|
|
64
|
+
public static func decryptBundleChecksum(checksum: String, publicKey: String) throws -> BundleChecksum {
|
|
35
65
|
if publicKey.isEmpty {
|
|
36
66
|
logger.info("No encryption set (public key) ignored")
|
|
37
|
-
return checksum
|
|
67
|
+
return BundleChecksum(plain: checksum, ciphertext: nil)
|
|
38
68
|
}
|
|
39
69
|
do {
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
logger.error("Cannot decode checksum as hex")
|
|
48
|
-
logger.debug("Checksum value: \(checksum)")
|
|
49
|
-
throw CustomError.cannotDecode
|
|
50
|
-
}
|
|
51
|
-
checksumBytes = hexData
|
|
52
|
-
detectedFormat = "hex"
|
|
53
|
-
} else {
|
|
54
|
-
// TODO: remove backwards compatibility
|
|
55
|
-
// Base64 encoded (old format for backwards compatibility)
|
|
56
|
-
guard let base64Data = Data(base64Encoded: checksum) else {
|
|
57
|
-
logger.error("Cannot decode checksum as base64")
|
|
58
|
-
logger.debug("Checksum value: \(checksum)")
|
|
59
|
-
throw CustomError.cannotDecode
|
|
60
|
-
}
|
|
61
|
-
checksumBytes = base64Data
|
|
62
|
-
detectedFormat = "base64"
|
|
70
|
+
// The encrypted checksum is hex encoded. The base64 format of CLI uploads made for plugin
|
|
71
|
+
// versions older than 5.30.0 / 6.30.0 / 7.30.0 is no longer accepted since 9.0.0.
|
|
72
|
+
// An odd length is rejected too: hexStringToData would silently drop the last digit.
|
|
73
|
+
guard checksum.count.isMultiple(of: 2), isHexString(checksum), let checksumBytes = hexStringToData(checksum) else {
|
|
74
|
+
logger.error("Cannot decode checksum as hex. Re-upload the bundle with a current Capgo CLI.")
|
|
75
|
+
logger.debug("Checksum value: \(checksum)")
|
|
76
|
+
throw CustomError.cannotDecode
|
|
63
77
|
}
|
|
64
|
-
|
|
65
|
-
logger.debug("Received checksum format: \(detectedFormat) (length: \(checksum.count) chars, \(checksumBytes.count) bytes)")
|
|
78
|
+
logger.debug("Received checksum format: hex (length: \(checksum.count) chars, \(checksumBytes.count) bytes)")
|
|
66
79
|
|
|
67
80
|
if checksumBytes.isEmpty {
|
|
68
81
|
logger.error("Decoded checksum is empty")
|
|
@@ -87,24 +100,15 @@ public struct CryptoCipher {
|
|
|
87
100
|
throw NSError(domain: "Failed to decrypt session key data", code: 2, userInfo: nil)
|
|
88
101
|
}
|
|
89
102
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
let detectedAlgorithm: String
|
|
95
|
-
if decryptedChecksum.count == 32 {
|
|
96
|
-
detectedAlgorithm = "SHA-256"
|
|
97
|
-
} else if decryptedChecksum.count == 4 {
|
|
98
|
-
detectedAlgorithm = "CRC32 (deprecated)"
|
|
99
|
-
logger.error("CRC32 checksum detected - deprecated algorithm")
|
|
100
|
-
} else {
|
|
101
|
-
detectedAlgorithm = "unknown (\(decryptedChecksum.count) bytes)"
|
|
102
|
-
logger.error("Unknown checksum algorithm detected")
|
|
103
|
-
logger.debug("Byte count: \(decryptedChecksum.count), Expected: 32 (SHA-256)")
|
|
103
|
+
guard decryptedChecksum.count == signedChecksumPayloadBytes else {
|
|
104
|
+
logger.error("Signed checksum has no ciphertext digest. Re-upload the bundle with a Capgo CLI that supports updater 9.")
|
|
105
|
+
logger.debug("Decrypted checksum bytes: \(decryptedChecksum.count), expected: \(signedChecksumPayloadBytes)")
|
|
106
|
+
throw CustomError.cannotDecode
|
|
104
107
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
+
|
|
109
|
+
let hex = decryptedChecksum.map { String(format: "%02x", $0) }.joined()
|
|
110
|
+
logger.debug("Decrypted checksum: SHA-256 of plaintext and ciphertext (64 bytes)")
|
|
111
|
+
return BundleChecksum(plain: String(hex.prefix(64)), ciphertext: String(hex.suffix(64)))
|
|
108
112
|
} catch {
|
|
109
113
|
logger.error("Checksum decryption failed")
|
|
110
114
|
logger.debug("Error: \(error.localizedDescription)")
|
|
@@ -112,9 +116,28 @@ public struct CryptoCipher {
|
|
|
112
116
|
}
|
|
113
117
|
}
|
|
114
118
|
|
|
119
|
+
/// Returns the SHA-256 of the plaintext from the signed bundle checksum, or `checksum` unchanged when no public
|
|
120
|
+
/// key is configured. See `decryptBundleChecksum(checksum:publicKey:)`.
|
|
121
|
+
public static func decryptChecksum(checksum: String, publicKey: String) throws -> String {
|
|
122
|
+
try decryptBundleChecksum(checksum: checksum, publicKey: publicKey).plain
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/// Rejects `filePath` unless its SHA-256 equals the signed ciphertext checksum. Runs before decryption, so
|
|
126
|
+
/// CBC padding is only ever checked on signed ciphertext.
|
|
127
|
+
static func verifyCiphertextChecksum(filePath: URL, expectedCiphertextSha256: String?) throws {
|
|
128
|
+
guard let expected = expectedCiphertextSha256, expected.count == 64, isHexString(expected) else {
|
|
129
|
+
throw CiphertextChecksumError.missing
|
|
130
|
+
}
|
|
131
|
+
let actual = try calcChecksumOrThrow(filePath: filePath)
|
|
132
|
+
if actual.lowercased() != expected.lowercased() {
|
|
133
|
+
logger.error("Encrypted file checksum mismatch, refusing to decrypt")
|
|
134
|
+
logger.debug("Expected: \(expected), Got: \(actual)")
|
|
135
|
+
throw CiphertextChecksumError.mismatch
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
115
139
|
/// Detect checksum algorithm based on hex string length.
|
|
116
|
-
/// SHA-256 = 64 hex chars (32 bytes)
|
|
117
|
-
/// CRC32 = 8 hex chars (4 bytes)
|
|
140
|
+
/// SHA-256 = 64 hex chars (32 bytes). It is the only supported algorithm.
|
|
118
141
|
public static func detectChecksumAlgorithm(_ hexChecksum: String) -> String {
|
|
119
142
|
if hexChecksum.isEmpty {
|
|
120
143
|
return "empty"
|
|
@@ -122,20 +145,16 @@ public struct CryptoCipher {
|
|
|
122
145
|
let len = hexChecksum.count
|
|
123
146
|
if len == 64 {
|
|
124
147
|
return "SHA-256"
|
|
125
|
-
} else if len == 8 {
|
|
126
|
-
return "CRC32 (deprecated)"
|
|
127
148
|
} else {
|
|
128
149
|
return "unknown (\(len) hex chars)"
|
|
129
150
|
}
|
|
130
151
|
}
|
|
131
152
|
|
|
132
|
-
/// Log checksum info and warn if
|
|
153
|
+
/// Log checksum info and warn if the checksum is not SHA-256.
|
|
133
154
|
public static func logChecksumInfo(label: String, hexChecksum: String) {
|
|
134
155
|
let algorithm = detectChecksumAlgorithm(hexChecksum)
|
|
135
156
|
logger.debug("\(label): \(algorithm) hex format (length: \(hexChecksum.count) chars)")
|
|
136
|
-
if algorithm.contains("
|
|
137
|
-
logger.error("CRC32 checksum detected - deprecated algorithm")
|
|
138
|
-
} else if algorithm.contains("unknown") {
|
|
157
|
+
if algorithm.contains("unknown") {
|
|
139
158
|
logger.error("Unknown checksum algorithm detected")
|
|
140
159
|
logger.debug("Char count: \(hexChecksum.count), Expected: 64 (SHA-256)")
|
|
141
160
|
}
|
|
@@ -215,12 +234,17 @@ public struct CryptoCipher {
|
|
|
215
234
|
return sessionKeyParts.count == 2 && !sessionKeyParts[0].isEmpty && !sessionKeyParts[1].isEmpty
|
|
216
235
|
}
|
|
217
236
|
|
|
218
|
-
|
|
237
|
+
/// Decrypts `filePath` in place. `expectedCiphertextSha256` is `BundleChecksum.ciphertext`: the file is hashed
|
|
238
|
+
/// and rejected before any AES work when it does not match.
|
|
239
|
+
public static func decryptFile(
|
|
240
|
+
filePath: URL, publicKey: String, sessionKey: String, version: String, expectedCiphertextSha256: String?
|
|
241
|
+
) throws {
|
|
219
242
|
if publicKey.isEmpty || !isValidSessionKey(sessionKey) {
|
|
220
243
|
logger.info("Encryption not set, no public key or session, ignored")
|
|
221
244
|
return
|
|
222
245
|
}
|
|
223
|
-
try DecryptionSession(publicKey: publicKey, sessionKey: sessionKey)
|
|
246
|
+
try DecryptionSession(publicKey: publicKey, sessionKey: sessionKey)
|
|
247
|
+
.decryptFile(filePath: filePath, expectedCiphertextSha256: expectedCiphertextSha256)
|
|
224
248
|
}
|
|
225
249
|
|
|
226
250
|
// Scoped to one manifest. Key material is immutable; CBC state stays local to each file.
|
|
@@ -248,11 +272,13 @@ public struct CryptoCipher {
|
|
|
248
272
|
!publicKey.isEmpty
|
|
249
273
|
}
|
|
250
274
|
|
|
251
|
-
func decryptFile(filePath: URL) throws {
|
|
275
|
+
func decryptFile(filePath: URL, expectedCiphertextSha256: String?) throws {
|
|
252
276
|
guard isEncrypted else {
|
|
253
277
|
CryptoCipher.logger.info("Encryption not set, no public key or session, ignored")
|
|
254
278
|
return
|
|
255
279
|
}
|
|
280
|
+
// Authenticate the encrypted bytes first: tampered ciphertext never reaches the cipher.
|
|
281
|
+
try CryptoCipher.verifyCiphertextChecksum(filePath: filePath, expectedCiphertextSha256: expectedCiphertextSha256)
|
|
256
282
|
try CryptoCipher.decryptPreparedFile(filePath: filePath, aesPrivateKey: key())
|
|
257
283
|
}
|
|
258
284
|
}
|
|
@@ -71,3 +71,27 @@ final class RedirectPolicyDelegate: NSObject, URLSessionTaskDelegate {
|
|
|
71
71
|
completionHandler(request)
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
|
+
|
|
75
|
+
/// Task delegate attached only to https bundle and manifest download tasks, to log the negotiated protocol.
|
|
76
|
+
/// The session delegate (`RedirectPolicyDelegate`) does not collect metrics, so plain http downloads and API calls
|
|
77
|
+
/// keep the exact same delegate setup as before. Redirects still reach the session delegate, because this one does not
|
|
78
|
+
/// implement them. Must not retain the updater strongly.
|
|
79
|
+
final class DownloadMetricsDelegate: NSObject, URLSessionTaskDelegate {
|
|
80
|
+
/// Set once when the updater session is created, before any task runs.
|
|
81
|
+
var onMetrics: ((URLSessionTask, URLSessionTaskMetrics) -> Void)?
|
|
82
|
+
|
|
83
|
+
func urlSession(_: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
|
|
84
|
+
onMetrics?(task, metrics)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
extension CapgoUpdater {
|
|
89
|
+
/// ALPN name of the last transaction that hit the network ("h3", "h2", "http/1.1"), nil when none did.
|
|
90
|
+
static func networkProtocol(of metrics: URLSessionTaskMetrics) -> String? {
|
|
91
|
+
return networkProtocol(of: metrics.transactionMetrics.map { $0.networkProtocolName })
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
static func networkProtocol(of names: [String?]) -> String? {
|
|
95
|
+
return names.last(where: { !($0 ?? "").isEmpty }) ?? nil
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -671,6 +671,7 @@ extension UIWindow {
|
|
|
671
671
|
let setResult = updater.setChannel(
|
|
672
672
|
channel: name,
|
|
673
673
|
defaultChannelKey: "CapacitorUpdater.defaultChannel",
|
|
674
|
+
defaultChannelFromSetChannelKey: CapacitorUpdaterPlugin.defaultChannelFromSetChannelStorageKey,
|
|
674
675
|
allowSetDefaultChannel: plugin.allowSetDefaultChannel,
|
|
675
676
|
configDefaultChannel: plugin.getConfig().getString("defaultChannel", "") ?? ""
|
|
676
677
|
)
|
|
@@ -800,7 +801,7 @@ extension UIWindow {
|
|
|
800
801
|
bridge: bridge,
|
|
801
802
|
onReload: {
|
|
802
803
|
_ = updater.set(bundle: bundle)
|
|
803
|
-
_ = plugin.
|
|
804
|
+
_ = plugin.reloadCurrentBundle()
|
|
804
805
|
}
|
|
805
806
|
)
|
|
806
807
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import WebKit
|
|
3
|
+
|
|
4
|
+
// Swift overlay WebKit callAsyncJavaScript autolinks libswiftWebKit.dylib (iOS 26+ on device).
|
|
5
|
+
// Use __callAsyncJavaScript via capgo_callAsyncJavaScriptInPage for sub-iOS 26 launch. Issue #1004.
|
|
6
|
+
extension WKWebView {
|
|
7
|
+
func capgo_callAsyncJavaScriptInPage(
|
|
8
|
+
_ script: String,
|
|
9
|
+
arguments: [String: Any] = [:],
|
|
10
|
+
completionHandler: @escaping (Any?, Error?) -> Void
|
|
11
|
+
) {
|
|
12
|
+
self.__callAsyncJavaScript(
|
|
13
|
+
script,
|
|
14
|
+
arguments: arguments,
|
|
15
|
+
inFrame: nil,
|
|
16
|
+
in: .page,
|
|
17
|
+
completionHandler: completionHandler
|
|
18
|
+
)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import XCTest
|
|
3
|
+
@testable import CapacitorUpdaterPlugin
|
|
4
|
+
|
|
5
|
+
private final class TestableCapgoUpdater: CapgoUpdater {
|
|
6
|
+
var builtinFolderOverride = FileManager.default.temporaryDirectory.appendingPathComponent("builtin-hashes-\(UUID().uuidString)")
|
|
7
|
+
|
|
8
|
+
override func builtinFolderURL() -> URL {
|
|
9
|
+
builtinFolderOverride
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
final class BuiltinHashesTests: XCTestCase {
|
|
14
|
+
private var implementation: TestableCapgoUpdater!
|
|
15
|
+
private var builtinFolder: URL {
|
|
16
|
+
implementation.builtinFolderOverride
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
override func setUpWithError() throws {
|
|
20
|
+
try super.setUpWithError()
|
|
21
|
+
CryptoCipher.setLogger(Logger(withTag: "BuiltinHashesTests", options: Logger.Options(level: .silent)))
|
|
22
|
+
implementation = TestableCapgoUpdater()
|
|
23
|
+
try FileManager.default.createDirectory(at: builtinFolder, withIntermediateDirectories: true)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
override func tearDown() {
|
|
27
|
+
try? FileManager.default.removeItem(at: builtinFolder)
|
|
28
|
+
implementation = nil
|
|
29
|
+
CryptoCipher.setLogger(Logger(withTag: "TestLogger"))
|
|
30
|
+
super.tearDown()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
private func writeHashTable(files: [String: String], sizes: [String: Int64]? = nil) throws {
|
|
34
|
+
var filesPayload: [String: Any] = [:]
|
|
35
|
+
for (key, hash) in files {
|
|
36
|
+
if let size = sizes?[key] {
|
|
37
|
+
filesPayload[key] = ["sha256": hash, "size": size]
|
|
38
|
+
} else {
|
|
39
|
+
let fileURL = builtinFolder.appendingPathComponent(key)
|
|
40
|
+
if FileManager.default.fileExists(atPath: fileURL.path),
|
|
41
|
+
let fileSize = try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize {
|
|
42
|
+
filesPayload[key] = ["sha256": hash, "size": Int64(fileSize)]
|
|
43
|
+
} else {
|
|
44
|
+
filesPayload[key] = ["sha256": hash]
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
let payload: [String: Any] = ["files": filesPayload]
|
|
49
|
+
let data = try JSONSerialization.data(withJSONObject: payload)
|
|
50
|
+
try data.write(to: builtinFolder.appendingPathComponent(CapgoUpdater.builtinHashesFileName))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
func testGetMissingBundleFilesFallsBackToHashingWhenTableSizeStale() throws {
|
|
54
|
+
let content = "stale size row \(UUID().uuidString)"
|
|
55
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
56
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
57
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
58
|
+
let tableHash = String(repeating: "b", count: 64)
|
|
59
|
+
let staleSize = Int64((try fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) + 99)
|
|
60
|
+
try writeHashTable(files: ["index.html": tableHash], sizes: ["index.html": staleSize])
|
|
61
|
+
let manifest = [
|
|
62
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
63
|
+
]
|
|
64
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
func testGetMissingBundleFilesUsesHashTableWithoutReadingBuiltinFile() throws {
|
|
68
|
+
let content = "table match \(UUID().uuidString)"
|
|
69
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
70
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
71
|
+
let expectedHash = String(repeating: "a", count: 64)
|
|
72
|
+
try writeHashTable(files: ["index.html": expectedHash])
|
|
73
|
+
let manifest = [
|
|
74
|
+
ManifestEntry(file_name: "index.html", file_hash: expectedHash, download_url: nil)
|
|
75
|
+
]
|
|
76
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
func testGetMissingBundleFilesReportsMissingWhenTableMatchesButFileAbsent() throws {
|
|
80
|
+
let expectedHash = String(repeating: "a", count: 64)
|
|
81
|
+
try writeHashTable(files: ["index.html": expectedHash])
|
|
82
|
+
let manifest = [
|
|
83
|
+
ManifestEntry(file_name: "index.html", file_hash: expectedHash, download_url: nil)
|
|
84
|
+
]
|
|
85
|
+
XCTAssertEqual(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").count, 1)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
func testGetMissingBundleFilesReportsMissingWhenHashTableDisagrees() throws {
|
|
89
|
+
let content = "table mismatch \(UUID().uuidString)"
|
|
90
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
91
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
92
|
+
let manifestHash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
93
|
+
let tableHash = String(repeating: "b", count: 64)
|
|
94
|
+
try writeHashTable(files: ["index.html": tableHash])
|
|
95
|
+
let manifest = [
|
|
96
|
+
ManifestEntry(file_name: "index.html", file_hash: manifestHash, download_url: nil)
|
|
97
|
+
]
|
|
98
|
+
XCTAssertEqual(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").count, 1)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
func testGetMissingBundleFilesFallsBackToHashingWhenPathNotInTable() throws {
|
|
102
|
+
let content = "fallback content \(UUID().uuidString)"
|
|
103
|
+
let fileURL = builtinFolder.appendingPathComponent("app.js")
|
|
104
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
105
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
106
|
+
try writeHashTable(files: ["other.js": hash])
|
|
107
|
+
let manifest = [
|
|
108
|
+
ManifestEntry(file_name: "app.js", file_hash: hash, download_url: nil)
|
|
109
|
+
]
|
|
110
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
func testGetMissingBundleFilesFallsBackWhenTableEntryIsMalformed() throws {
|
|
114
|
+
let content = "malformed table \(UUID().uuidString)"
|
|
115
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
116
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
117
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
118
|
+
try writeHashTable(files: ["index.html": "not-a-sha256"])
|
|
119
|
+
let manifest = [
|
|
120
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
121
|
+
]
|
|
122
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
func testGetMissingBundleFilesFallsBackWhenTableSizeIsMalformed() throws {
|
|
126
|
+
let content = "malformed size \(UUID().uuidString)"
|
|
127
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
128
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
129
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
130
|
+
let tableHash = String(repeating: "c", count: 64)
|
|
131
|
+
let table = "{\"files\":{\"index.html\":{\"sha256\":\"\(tableHash)\",\"size\":\"not-a-number\"}}}"
|
|
132
|
+
try table.write(to: builtinFolder.appendingPathComponent(CapgoUpdater.builtinHashesFileName), atomically: true, encoding: .utf8)
|
|
133
|
+
let manifest = [
|
|
134
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
135
|
+
]
|
|
136
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
func testGetMissingBundleFilesFallsBackWhenHashTableMissingOrMalformed() throws {
|
|
140
|
+
let content = "no table \(UUID().uuidString)"
|
|
141
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
142
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
143
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
144
|
+
try "{ not json".write(to: builtinFolder.appendingPathComponent(CapgoUpdater.builtinHashesFileName), atomically: true, encoding: .utf8)
|
|
145
|
+
let manifest = [
|
|
146
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
147
|
+
]
|
|
148
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
func testBuiltinHashesTableReadOnceAcrossManyLookupsAndUpdates() throws {
|
|
152
|
+
let contentA = "entry a \(UUID().uuidString)"
|
|
153
|
+
let contentB = "entry b \(UUID().uuidString)"
|
|
154
|
+
let fileA = builtinFolder.appendingPathComponent("index.html")
|
|
155
|
+
let fileB = builtinFolder.appendingPathComponent("app.js")
|
|
156
|
+
try contentA.write(to: fileA, atomically: true, encoding: .utf8)
|
|
157
|
+
try contentB.write(to: fileB, atomically: true, encoding: .utf8)
|
|
158
|
+
let hashA = String(repeating: "d", count: 64)
|
|
159
|
+
let hashB = String(repeating: "e", count: 64)
|
|
160
|
+
try writeHashTable(files: ["index.html": hashA, "app.js": hashB])
|
|
161
|
+
|
|
162
|
+
for i in 0..<12 {
|
|
163
|
+
let manifest = [
|
|
164
|
+
ManifestEntry(file_name: "index.html", file_hash: hashA, download_url: nil),
|
|
165
|
+
ManifestEntry(file_name: "app.js", file_hash: hashB, download_url: nil)
|
|
166
|
+
]
|
|
167
|
+
if i.isMultiple(of: 2) {
|
|
168
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
169
|
+
} else {
|
|
170
|
+
_ = implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "")
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
XCTAssertEqual(implementation.builtinHashesTableLoadCount, 1)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
func testBuiltinHashesTableReadOnceWhenMissingOrMalformed() throws {
|
|
178
|
+
let content = "no valid table \(UUID().uuidString)"
|
|
179
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
180
|
+
try content.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
181
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
182
|
+
try "{ not json".write(to: builtinFolder.appendingPathComponent(CapgoUpdater.builtinHashesFileName), atomically: true, encoding: .utf8)
|
|
183
|
+
|
|
184
|
+
for _ in 0..<8 {
|
|
185
|
+
let manifest = [
|
|
186
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
187
|
+
]
|
|
188
|
+
XCTAssertTrue(implementation.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
XCTAssertEqual(implementation.builtinHashesTableLoadCount, 1)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
func testGetMissingBundleFilesFallsBackWhenTableSizeIsBoolean() throws {
|
|
195
|
+
let fileURL = builtinFolder.appendingPathComponent("index.html")
|
|
196
|
+
try "x".write(to: fileURL, atomically: true, encoding: .utf8)
|
|
197
|
+
let hash = CryptoCipher.calcChecksum(filePath: fileURL)
|
|
198
|
+
let tableHash = String(repeating: "c", count: 64)
|
|
199
|
+
for size in ["true", "-5", "0.5"] {
|
|
200
|
+
let table = "{\"files\":{\"index.html\":{\"sha256\":\"\(tableHash)\",\"size\":\(size)}}}"
|
|
201
|
+
try table.write(to: builtinFolder.appendingPathComponent(CapgoUpdater.builtinHashesFileName), atomically: true, encoding: .utf8)
|
|
202
|
+
let manifest = [
|
|
203
|
+
ManifestEntry(file_name: "index.html", file_hash: hash, download_url: nil)
|
|
204
|
+
]
|
|
205
|
+
let updater = TestableCapgoUpdater()
|
|
206
|
+
updater.builtinFolderOverride = builtinFolder
|
|
207
|
+
XCTAssertTrue(updater.getMissingBundleFiles(manifest: manifest, sessionKey: "").isEmpty, "size \(size)")
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|