@capgo/capacitor-updater 9.0.0 → 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 +3 -6
- package/Package.swift +30 -0
- package/README.md +2382 -292
- package/android/build.gradle +37 -15
- package/android/consumer-rules.pro +48 -0
- package/android/proguard-rules.pro +23 -0
- package/android/src/main/AndroidManifest.xml +0 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
- package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
- package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
- package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
- 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/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
- package/dist/docs.json +4431 -840
- package/dist/esm/definitions.d.ts +2607 -225
- package/dist/esm/definitions.js +103 -1
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/history.d.ts +1 -0
- package/dist/esm/history.js +283 -0
- package/dist/esm/history.js.map +1 -0
- package/dist/esm/index.d.ts +3 -2
- package/dist/esm/index.js +5 -4
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/web.d.ts +53 -42
- package/dist/esm/web.js +180 -37
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +570 -37
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +570 -37
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
- package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
- package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
- package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
- package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
- package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
- package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
- package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
- package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
- package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
- package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
- package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
- package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
- package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -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 +80 -43
- package/scripts/builtin-hashes-lib.mjs +148 -0
- package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
- package/scripts/resolve-real-path.mjs +25 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
- package/ios/Plugin/BundleInfo.swift +0 -113
- package/ios/Plugin/BundleStatus.swift +0 -48
- package/ios/Plugin/CapacitorUpdater.swift +0 -858
- package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
- package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
- package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
- package/ios/Plugin/CryptoCipher.swift +0 -240
- /package/{LICENCE → LICENSE} +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
- /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import XCTest
|
|
3
|
+
@testable import CapacitorUpdaterPlugin
|
|
4
|
+
|
|
5
|
+
final class InstallPerfTests: XCTestCase {
|
|
6
|
+
private let zipFiles = 512
|
|
7
|
+
private let zipFileBytes = 64 * 1024
|
|
8
|
+
private let manifestFiles = 10_000
|
|
9
|
+
private let manifestFileBytes = 2048
|
|
10
|
+
private let runs = 3
|
|
11
|
+
private let oldZipBuffer = 16 * 1024
|
|
12
|
+
|
|
13
|
+
func testCompareZipAndManifestInstallBeforeAfter() throws {
|
|
14
|
+
let root = FileManager.default.temporaryDirectory.appendingPathComponent("capgo-install-perf-\(UUID().uuidString)")
|
|
15
|
+
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
16
|
+
defer { try? FileManager.default.removeItem(at: root) }
|
|
17
|
+
|
|
18
|
+
let zipURL = root.appendingPathComponent("bundle.zip")
|
|
19
|
+
try writeStoredZip(to: zipURL, fileCount: zipFiles, fileBytes: zipFileBytes)
|
|
20
|
+
let zipBytes = (try FileManager.default.attributesOfItem(atPath: zipURL.path)[.size] as? NSNumber)?.intValue ?? 0
|
|
21
|
+
print("CAPGO_INSTALL_PERF platform=ios fixture=zip files=\(zipFiles) bytes_each=\(zipFileBytes) zip_bytes=\(zipBytes)")
|
|
22
|
+
|
|
23
|
+
var unzipBefore: [Int64] = []
|
|
24
|
+
var unzipAfter: [Int64] = []
|
|
25
|
+
for i in 0..<runs {
|
|
26
|
+
unzipBefore.append(try timeUnzip(root: root, zipURL: zipURL, id: "unzip-before-\(i)", bufferSize: oldZipBuffer))
|
|
27
|
+
unzipAfter.append(try timeUnzip(root: root, zipURL: zipURL, id: "unzip-after-\(i)", bufferSize: CryptoCipher.ioBufferBytes()))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let builtin = root.appendingPathComponent("builtin")
|
|
31
|
+
try FileManager.default.createDirectory(at: builtin, withIntermediateDirectories: true)
|
|
32
|
+
var sources: [URL] = []
|
|
33
|
+
var hashes: [String] = []
|
|
34
|
+
var payload = Data(repeating: 0x11, count: manifestFileBytes)
|
|
35
|
+
for i in 0..<manifestFiles {
|
|
36
|
+
payload[0] = UInt8(i & 0xff)
|
|
37
|
+
payload[1] = UInt8((i >> 8) & 0xff)
|
|
38
|
+
payload[2] = UInt8((i >> 16) & 0xff)
|
|
39
|
+
let source = builtin.appendingPathComponent("f\(i).js")
|
|
40
|
+
try payload.write(to: source)
|
|
41
|
+
sources.append(source)
|
|
42
|
+
hashes.append(CryptoCipher.calcChecksum(filePath: source))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
var manifestBefore: [Int64] = []
|
|
46
|
+
var manifestAfter: [Int64] = []
|
|
47
|
+
for i in 0..<runs {
|
|
48
|
+
manifestBefore.append(try timeManifestSequential1KiB(root: root, name: "manifest-before-\(i)", sources: sources, hashes: hashes))
|
|
49
|
+
manifestAfter.append(try timeManifestProduction(root: root, name: "manifest-after-\(i)", sources: sources, hashes: hashes))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
printResult(platform: "ios", scenario: "unzip_32mb_512files", before: unzipBefore, after: unzipAfter)
|
|
53
|
+
printResult(platform: "ios", scenario: "manifest_10k_builtin_copy", before: manifestBefore, after: manifestAfter)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private func timeUnzip(root: URL, zipURL: URL, id: String, bufferSize: Int) throws -> Int64 {
|
|
57
|
+
let updater = CapgoUpdater()
|
|
58
|
+
updater.setLogger(Logger(withTag: "install-perf", options: Logger.Options(level: .silent)))
|
|
59
|
+
let zipCopy = root.appendingPathComponent("\(id).zip")
|
|
60
|
+
try? FileManager.default.removeItem(at: zipCopy)
|
|
61
|
+
try FileManager.default.copyItem(at: zipURL, to: zipCopy)
|
|
62
|
+
let persist = root.appendingPathComponent(id)
|
|
63
|
+
try? FileManager.default.removeItem(at: persist)
|
|
64
|
+
let start = DispatchTime.now().uptimeNanoseconds
|
|
65
|
+
try updater.saveDownloaded(sourceZip: zipCopy, id: id, base: root, notify: false, bufferSize: bufferSize)
|
|
66
|
+
let elapsed = Int64((DispatchTime.now().uptimeNanoseconds - start) / 1_000_000)
|
|
67
|
+
XCTAssertEqual(zipFiles, try countFiles(in: persist))
|
|
68
|
+
return elapsed
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private func timeManifestProduction(root: URL, name: String, sources: [URL], hashes: [String]) throws -> Int64 {
|
|
72
|
+
let updater = CapgoUpdater()
|
|
73
|
+
updater.setLogger(Logger(withTag: "install-perf", options: Logger.Options(level: .silent)))
|
|
74
|
+
let destDir = root.appendingPathComponent(name)
|
|
75
|
+
try? FileManager.default.removeItem(at: destDir)
|
|
76
|
+
try FileManager.default.createDirectory(at: destDir, withIntermediateDirectories: true)
|
|
77
|
+
let files = Swift.zip(sources, hashes).map { source, hash in
|
|
78
|
+
(source: source, dest: destDir.appendingPathComponent(source.lastPathComponent), hash: hash)
|
|
79
|
+
}
|
|
80
|
+
let start = DispatchTime.now().uptimeNanoseconds
|
|
81
|
+
try updater.copyMatchingBuiltinFilesForTests(files: files)
|
|
82
|
+
let elapsed = Int64((DispatchTime.now().uptimeNanoseconds - start) / 1_000_000)
|
|
83
|
+
XCTAssertEqual(manifestFiles, try countFiles(in: destDir))
|
|
84
|
+
return elapsed
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private func timeManifestSequential1KiB(root: URL, name: String, sources: [URL], hashes: [String]) throws -> Int64 {
|
|
88
|
+
let destDir = root.appendingPathComponent(name)
|
|
89
|
+
try? FileManager.default.removeItem(at: destDir)
|
|
90
|
+
try FileManager.default.createDirectory(at: destDir, withIntermediateDirectories: true)
|
|
91
|
+
let queue = OperationQueue()
|
|
92
|
+
queue.maxConcurrentOperationCount = CapgoUpdater.manifestMaxConcurrentFiles
|
|
93
|
+
let start = DispatchTime.now().uptimeNanoseconds
|
|
94
|
+
let lock = NSLock()
|
|
95
|
+
var firstError: Error?
|
|
96
|
+
for (source, hash) in Swift.zip(sources, hashes) {
|
|
97
|
+
queue.addOperation {
|
|
98
|
+
do {
|
|
99
|
+
let actual = Self.sha256OneKiB(file: source)
|
|
100
|
+
guard actual.lowercased() == hash.lowercased() else {
|
|
101
|
+
throw NSError(domain: "CapgoInstallPerf", code: 3, userInfo: [NSLocalizedDescriptionKey: "checksum mismatch"])
|
|
102
|
+
}
|
|
103
|
+
let dest = destDir.appendingPathComponent(source.lastPathComponent)
|
|
104
|
+
try FileManager.default.copyItem(at: source, to: dest)
|
|
105
|
+
} catch {
|
|
106
|
+
lock.lock()
|
|
107
|
+
if firstError == nil {
|
|
108
|
+
firstError = error
|
|
109
|
+
}
|
|
110
|
+
lock.unlock()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
queue.waitUntilAllOperationsAreFinished()
|
|
115
|
+
if let firstError {
|
|
116
|
+
throw firstError
|
|
117
|
+
}
|
|
118
|
+
let elapsed = Int64((DispatchTime.now().uptimeNanoseconds - start) / 1_000_000)
|
|
119
|
+
XCTAssertEqual(manifestFiles, try countFiles(in: destDir))
|
|
120
|
+
return elapsed
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private func printResult(platform: String, scenario: String, before: [Int64], after: [Int64]) {
|
|
124
|
+
print(
|
|
125
|
+
"CAPGO_INSTALL_PERF platform=\(platform) scenario=\(scenario) before_ms=\(median(before)) after_ms=\(median(after)) before_runs=\(before) after_runs=\(after)"
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private func median(_ values: [Int64]) -> Int64 {
|
|
130
|
+
let sorted = values.sorted()
|
|
131
|
+
return sorted[sorted.count / 2]
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private func writeStoredZip(to zipURL: URL, fileCount: Int, fileBytes: Int) throws {
|
|
135
|
+
var writer = TestZipWriter()
|
|
136
|
+
for index in 0..<fileCount {
|
|
137
|
+
var payload = Data(repeating: UInt8(index & 0xff), count: fileBytes)
|
|
138
|
+
payload[0] = UInt8(index & 0xff)
|
|
139
|
+
payload[1] = UInt8((index >> 8) & 0xff)
|
|
140
|
+
writer.addFile("www/f\(index).js", payload)
|
|
141
|
+
}
|
|
142
|
+
try writer.write(to: zipURL)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private func countFiles(in dir: URL) throws -> Int {
|
|
146
|
+
let entries = try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.isDirectoryKey], options: [])
|
|
147
|
+
var count = 0
|
|
148
|
+
for entry in entries {
|
|
149
|
+
let isDir = (try entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
|
|
150
|
+
if isDir {
|
|
151
|
+
count += try countFiles(in: entry)
|
|
152
|
+
} else {
|
|
153
|
+
count += 1
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return count
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private static func sha256OneKiB(file: URL) -> String {
|
|
160
|
+
guard let handle = try? FileHandle(forReadingFrom: file) else {
|
|
161
|
+
return ""
|
|
162
|
+
}
|
|
163
|
+
defer { try? handle.close() }
|
|
164
|
+
var hasher = CryptoCipher.RunningChecksum()
|
|
165
|
+
while true {
|
|
166
|
+
let chunk = (try? handle.read(upToCount: 1024)) ?? Data()
|
|
167
|
+
if chunk.isEmpty {
|
|
168
|
+
break
|
|
169
|
+
}
|
|
170
|
+
hasher.update(chunk)
|
|
171
|
+
}
|
|
172
|
+
return hasher.hex()
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import XCTest
|
|
3
|
+
@testable import CapacitorUpdaterPlugin
|
|
4
|
+
|
|
5
|
+
private final class ListChannelsRequestCapgoUpdater: CapgoUpdater {
|
|
6
|
+
private let requestResult: CapgoUpdater.RequestResult
|
|
7
|
+
|
|
8
|
+
init(requestResult: CapgoUpdater.RequestResult) {
|
|
9
|
+
self.requestResult = requestResult
|
|
10
|
+
super.init()
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
override func performRequest(_: URLRequest, label _: String) -> CapgoUpdater.RequestResult {
|
|
14
|
+
requestResult
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
final class ListChannelsTests: XCTestCase {
|
|
19
|
+
private let channelScheme = "https"
|
|
20
|
+
private let channelHost = "example.com"
|
|
21
|
+
private let channelPathComponent = "channel"
|
|
22
|
+
|
|
23
|
+
func testListChannelsDecodesNumericChannelIdsAsNumbers() throws {
|
|
24
|
+
let channelURL = try makeChannelURL()
|
|
25
|
+
let response = try XCTUnwrap(HTTPURLResponse(url: channelURL, statusCode: 200, httpVersion: nil, headerFields: nil))
|
|
26
|
+
let responseData = Data("""
|
|
27
|
+
[
|
|
28
|
+
{"id":123,"name":"Production","public":true,"allow_self_set":true},
|
|
29
|
+
{"id":456,"name":"Beta","public":false,"allow_self_set":true}
|
|
30
|
+
]
|
|
31
|
+
""".utf8)
|
|
32
|
+
let requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
|
|
33
|
+
let updater = ListChannelsRequestCapgoUpdater(requestResult: requestResult)
|
|
34
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
35
|
+
updater.channelUrl = channelURL.absoluteString
|
|
36
|
+
|
|
37
|
+
let result = updater.listChannels()
|
|
38
|
+
|
|
39
|
+
XCTAssertEqual(result.error, "")
|
|
40
|
+
XCTAssertEqual(result.channels.count, 2)
|
|
41
|
+
XCTAssertEqual(result.channels[0]["id"] as? Int, 123)
|
|
42
|
+
XCTAssertEqual(result.channels[0]["name"] as? String, "Production")
|
|
43
|
+
XCTAssertEqual(result.channels[0]["public"] as? Bool, true)
|
|
44
|
+
XCTAssertEqual(result.channels[0]["allow_self_set"] as? Bool, true)
|
|
45
|
+
XCTAssertEqual(result.channels[1]["id"] as? Int, 456)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
func testListChannelsRejectsStringChannelIds() throws {
|
|
49
|
+
let channelURL = try makeChannelURL()
|
|
50
|
+
let response = try XCTUnwrap(HTTPURLResponse(url: channelURL, statusCode: 200, httpVersion: nil, headerFields: nil))
|
|
51
|
+
let responseData = Data("""
|
|
52
|
+
[
|
|
53
|
+
{"id":"123","name":"Production","public":true,"allow_self_set":true}
|
|
54
|
+
]
|
|
55
|
+
""".utf8)
|
|
56
|
+
let requestResult = CapgoUpdater.RequestResult(data: responseData, response: response, error: nil, timedOut: false)
|
|
57
|
+
let updater = ListChannelsRequestCapgoUpdater(requestResult: requestResult)
|
|
58
|
+
updater.setLogger(Logger(withTag: "TestLogger"))
|
|
59
|
+
updater.channelUrl = channelURL.absoluteString
|
|
60
|
+
|
|
61
|
+
let result = updater.listChannels()
|
|
62
|
+
|
|
63
|
+
XCTAssertEqual(result.error, "decode_error")
|
|
64
|
+
XCTAssertEqual(result.channels.count, 0)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private func makeChannelURL() throws -> URL {
|
|
68
|
+
var components = URLComponents()
|
|
69
|
+
components.scheme = channelScheme
|
|
70
|
+
components.host = channelHost
|
|
71
|
+
components.path = "/" + channelPathComponent
|
|
72
|
+
return try XCTUnwrap(components.url)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import XCTest
|
|
2
|
+
import WebKit
|
|
3
|
+
@testable import CapacitorUpdaterPlugin
|
|
4
|
+
|
|
5
|
+
private final class RecordingWebView: WKWebView {
|
|
6
|
+
private(set) var lastScript: String?
|
|
7
|
+
|
|
8
|
+
override func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil) {
|
|
9
|
+
lastScript = javaScriptString
|
|
10
|
+
completionHandler?(nil, nil)
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
final class LoggerSecurityTests: XCTestCase {
|
|
15
|
+
private let injectionPayloads = [
|
|
16
|
+
"hello\");alert(1)//",
|
|
17
|
+
"line\nbreak",
|
|
18
|
+
"`backtick`",
|
|
19
|
+
"</script><script>alert(1)</script>",
|
|
20
|
+
"back\\slash",
|
|
21
|
+
"line\u{2028}separator",
|
|
22
|
+
"para\u{2029}graph",
|
|
23
|
+
"{\"error\":\"Internal Server Error\",\"detail\":\"');fetch('https://evil.test')//\"}",
|
|
24
|
+
"HTTP/1.1 500\r\n\r\n<script>alert(1)</script>"
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
func testToJSStringLiteralEscapesQuotesNewlinesBackslashesAndLineSeparators() throws {
|
|
28
|
+
let logger = Logger(withTag: "LoggerSecurityTests")
|
|
29
|
+
|
|
30
|
+
for payload in injectionPayloads {
|
|
31
|
+
try assertRoundTripJSStringLiteral(logger: logger, value: payload)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
func testBuildWebViewConsoleScriptUsesAllowlistedConsoleMethodsOnly() {
|
|
36
|
+
let logger = Logger(withTag: "CapgoUpdater")
|
|
37
|
+
|
|
38
|
+
XCTAssertEqual(
|
|
39
|
+
"console.error(\(logger.toJSStringLiteral("🟢 CapgoUpdater : test")))",
|
|
40
|
+
logger.buildWebViewConsoleScript(level: .error, label: "🟢", tag: "CapgoUpdater", message: "test")
|
|
41
|
+
)
|
|
42
|
+
XCTAssertEqual(
|
|
43
|
+
"console.warn(\(logger.toJSStringLiteral("🟠 CapgoUpdater : test")))",
|
|
44
|
+
logger.buildWebViewConsoleScript(level: .warn, label: "🟠", tag: "CapgoUpdater", message: "test")
|
|
45
|
+
)
|
|
46
|
+
XCTAssertEqual(
|
|
47
|
+
"console.info(\(logger.toJSStringLiteral("🟢 CapgoUpdater : test")))",
|
|
48
|
+
logger.buildWebViewConsoleScript(level: .info, label: "🟢", tag: "CapgoUpdater", message: "test")
|
|
49
|
+
)
|
|
50
|
+
XCTAssertEqual(
|
|
51
|
+
"console.debug(\(logger.toJSStringLiteral("🔎 CapgoUpdater : test")))",
|
|
52
|
+
logger.buildWebViewConsoleScript(level: .debug, label: "🔎", tag: "CapgoUpdater", message: "test")
|
|
53
|
+
)
|
|
54
|
+
XCTAssertNil(logger.buildWebViewConsoleScript(level: .silent, label: "", tag: "CapgoUpdater", message: "test"))
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
func testBuildWebViewConsoleScriptEscapesTagAndMessagePayloads() throws {
|
|
58
|
+
let logger = Logger(withTag: "LoggerSecurityTests")
|
|
59
|
+
|
|
60
|
+
for payload in injectionPayloads {
|
|
61
|
+
let script = logger.buildWebViewConsoleScript(
|
|
62
|
+
level: .error,
|
|
63
|
+
label: "🔴",
|
|
64
|
+
tag: "tag\");alert(1)//",
|
|
65
|
+
message: payload
|
|
66
|
+
)
|
|
67
|
+
XCTAssertNotNil(script)
|
|
68
|
+
try assertSafeConsoleScript(
|
|
69
|
+
script!,
|
|
70
|
+
consoleMethod: "error",
|
|
71
|
+
expectedPayload: "🔴 tag\");alert(1)// : \(payload)",
|
|
72
|
+
logger: logger
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
func testLogAtLevelForwardsEscapedScriptToEvaluateJavaScript() throws {
|
|
78
|
+
let logger = Logger(withTag: "CapgoUpdater")
|
|
79
|
+
let webView = RecordingWebView(frame: .zero, configuration: WKWebViewConfiguration())
|
|
80
|
+
logger.setWebView(webView: webView)
|
|
81
|
+
|
|
82
|
+
let maliciousMessage = "hello\");alert(1)//"
|
|
83
|
+
logger.log(atLevel: .error, message: maliciousMessage)
|
|
84
|
+
|
|
85
|
+
let expectation = expectation(description: "evaluateJavaScript dispatched")
|
|
86
|
+
DispatchQueue.main.async {
|
|
87
|
+
expectation.fulfill()
|
|
88
|
+
}
|
|
89
|
+
wait(for: [expectation], timeout: 1.0)
|
|
90
|
+
|
|
91
|
+
try assertSafeConsoleScript(
|
|
92
|
+
XCTUnwrap(webView.lastScript),
|
|
93
|
+
consoleMethod: "error",
|
|
94
|
+
expectedPayload: "🔴 CapgoUpdater : \(maliciousMessage)",
|
|
95
|
+
logger: logger
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
func testCapWebViewLogPayloadTruncatesOversizedMessages() {
|
|
100
|
+
let logger = Logger(withTag: "LoggerSecurityTests")
|
|
101
|
+
let oversized = String(repeating: "x", count: Logger.maxWebViewLogPayloadChars + 10)
|
|
102
|
+
let capped = logger.capWebViewLogPayload(oversized)
|
|
103
|
+
|
|
104
|
+
XCTAssertTrue(capped.hasSuffix("..."))
|
|
105
|
+
XCTAssertLessThanOrEqual(capped.utf8.count, Logger.maxWebViewLogPayloadChars + 3)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
func testCapWebViewLogPayloadPreservesValidUtf8Boundaries() {
|
|
109
|
+
let logger = Logger(withTag: "LoggerSecurityTests")
|
|
110
|
+
let prefix = String(repeating: "x", count: Logger.maxWebViewLogPayloadChars - 1)
|
|
111
|
+
let capped = logger.capWebViewLogPayload(prefix + "💡")
|
|
112
|
+
|
|
113
|
+
XCTAssertEqual(prefix + "...", capped)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
func testCapWebViewLogPayloadPreservesCompleteScalarsAtByteLimit() {
|
|
117
|
+
let logger = Logger(withTag: "LoggerSecurityTests")
|
|
118
|
+
let prefix = String(repeating: "x", count: Logger.maxWebViewLogPayloadChars - 2)
|
|
119
|
+
let capped = logger.capWebViewLogPayload(prefix + "éoverflow")
|
|
120
|
+
|
|
121
|
+
XCTAssertEqual(prefix + "é...", capped)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private func assertSafeConsoleScript(
|
|
125
|
+
_ script: String,
|
|
126
|
+
consoleMethod: String,
|
|
127
|
+
expectedPayload: String,
|
|
128
|
+
logger: Logger
|
|
129
|
+
) throws {
|
|
130
|
+
let expectedScript = "console.\(consoleMethod)(\(logger.toJSStringLiteral(expectedPayload)))"
|
|
131
|
+
XCTAssertEqual(expectedScript, script)
|
|
132
|
+
|
|
133
|
+
let prefix = "console.\(consoleMethod)("
|
|
134
|
+
let quotedArg = String(script.dropFirst(prefix.count).dropLast())
|
|
135
|
+
let data = Data(("[" + quotedArg + "]").utf8)
|
|
136
|
+
let decodedPayloads = try JSONDecoder().decode([String].self, from: data)
|
|
137
|
+
XCTAssertEqual(expectedPayload, decodedPayloads[0])
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private func assertRoundTripJSStringLiteral(logger: Logger, value: String) throws {
|
|
141
|
+
let quoted = logger.toJSStringLiteral(value)
|
|
142
|
+
XCTAssertTrue(quoted.hasPrefix("\""))
|
|
143
|
+
XCTAssertTrue(quoted.hasSuffix("\""))
|
|
144
|
+
|
|
145
|
+
let data = Data(("[" + quoted + "]").utf8)
|
|
146
|
+
let decodedPayloads = try JSONDecoder().decode([String].self, from: data)
|
|
147
|
+
XCTAssertEqual(value, decodedPayloads[0])
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import XCTest
|
|
3
|
+
@testable import CapacitorUpdaterPlugin
|
|
4
|
+
|
|
5
|
+
final class NativeContractTests: XCTestCase {
|
|
6
|
+
private static let contract: [String: Any] = {
|
|
7
|
+
do {
|
|
8
|
+
let data = try Data(contentsOf: contractFileURL())
|
|
9
|
+
let value = try JSONSerialization.jsonObject(with: data)
|
|
10
|
+
guard let contract = value as? [String: Any] else {
|
|
11
|
+
throw ContractError.invalidRoot
|
|
12
|
+
}
|
|
13
|
+
return contract
|
|
14
|
+
} catch {
|
|
15
|
+
XCTFail("Unable to load native contract fixture: \(error)")
|
|
16
|
+
return [:]
|
|
17
|
+
}
|
|
18
|
+
}()
|
|
19
|
+
|
|
20
|
+
private enum ContractError: Error {
|
|
21
|
+
case missingFixture
|
|
22
|
+
case invalidRoot
|
|
23
|
+
case invalidCases(String)
|
|
24
|
+
case invalidCase(String)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
private static func contractFileURL() throws -> URL {
|
|
28
|
+
let fileManager = FileManager.default
|
|
29
|
+
let roots = [
|
|
30
|
+
URL(fileURLWithPath: fileManager.currentDirectoryPath),
|
|
31
|
+
URL(fileURLWithPath: #filePath)
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
for root in roots {
|
|
35
|
+
var current = root
|
|
36
|
+
while current.path != "/" {
|
|
37
|
+
let candidate = current
|
|
38
|
+
.appendingPathComponent("native-contract-tests")
|
|
39
|
+
.appendingPathComponent("core.json")
|
|
40
|
+
if fileManager.fileExists(atPath: candidate.path) {
|
|
41
|
+
return candidate
|
|
42
|
+
}
|
|
43
|
+
current.deleteLastPathComponent()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
throw ContractError.missingFixture
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private func contractCases(_ key: String) throws -> [[String: Any]] {
|
|
50
|
+
guard let cases = Self.contract[key] as? [[String: Any]] else {
|
|
51
|
+
throw ContractError.invalidCases(key)
|
|
52
|
+
}
|
|
53
|
+
return cases
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private func dictionary(_ source: [String: Any], _ key: String, id: String) throws -> [String: Any] {
|
|
57
|
+
guard let value = source[key] as? [String: Any] else {
|
|
58
|
+
throw ContractError.invalidCase("\(id).\(key)")
|
|
59
|
+
}
|
|
60
|
+
return value
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private func int(_ source: [String: Any], _ key: String, id: String) throws -> Int {
|
|
64
|
+
guard let value = source[key] as? NSNumber else {
|
|
65
|
+
throw ContractError.invalidCase("\(id).\(key)")
|
|
66
|
+
}
|
|
67
|
+
return value.intValue
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private func bool(_ source: [String: Any], _ key: String, id: String) throws -> Bool {
|
|
71
|
+
guard let value = source[key] as? Bool else {
|
|
72
|
+
throw ContractError.invalidCase("\(id).\(key)")
|
|
73
|
+
}
|
|
74
|
+
return value
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private func string(_ source: [String: Any], _ key: String, id: String) throws -> String {
|
|
78
|
+
guard let value = source[key] as? String else {
|
|
79
|
+
throw ContractError.invalidCase("\(id).\(key)")
|
|
80
|
+
}
|
|
81
|
+
return value
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private func optionalString(_ source: [String: Any], _ key: String, id: String) throws -> String? {
|
|
85
|
+
guard let value = source[key], !(value is NSNull) else {
|
|
86
|
+
return nil
|
|
87
|
+
}
|
|
88
|
+
guard let stringValue = value as? String else {
|
|
89
|
+
throw ContractError.invalidCase("\(id).\(key) expected String or null")
|
|
90
|
+
}
|
|
91
|
+
return stringValue
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
func testPeriodCheckDelayMatchesNativeContract() throws {
|
|
95
|
+
for testCase in try contractCases("periodCheckDelay") {
|
|
96
|
+
let id = try string(testCase, "id", id: "periodCheckDelay")
|
|
97
|
+
let input = try dictionary(testCase, "input", id: id)
|
|
98
|
+
let expect = try dictionary(testCase, "expect", id: id)
|
|
99
|
+
|
|
100
|
+
XCTAssertEqual(
|
|
101
|
+
CapacitorUpdaterPlugin.normalizedPeriodCheckDelaySeconds(try int(input, "seconds", id: id)),
|
|
102
|
+
try int(expect, "normalizedSeconds", id: id),
|
|
103
|
+
id
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
func testAutoUpdateModeMatchesNativeContract() throws {
|
|
109
|
+
for testCase in try contractCases("autoUpdateMode") {
|
|
110
|
+
let id = try string(testCase, "id", id: "autoUpdateMode")
|
|
111
|
+
let input = try dictionary(testCase, "input", id: id)
|
|
112
|
+
let expect = try dictionary(testCase, "expect", id: id)
|
|
113
|
+
let normalizedMode = CapacitorUpdaterPlugin.normalizedAutoUpdateMode(try string(input, "mode", id: id))
|
|
114
|
+
|
|
115
|
+
XCTAssertEqual(normalizedMode, try string(expect, "mode", id: id), id)
|
|
116
|
+
XCTAssertEqual(CapacitorUpdaterPlugin.isAutoUpdateModeEnabled(normalizedMode), try bool(expect, "enabled", id: id), id)
|
|
117
|
+
XCTAssertEqual(
|
|
118
|
+
CapacitorUpdaterPlugin.directUpdateModeForAutoUpdateMode(normalizedMode),
|
|
119
|
+
try string(expect, "directUpdateMode", id: id),
|
|
120
|
+
id
|
|
121
|
+
)
|
|
122
|
+
XCTAssertEqual(
|
|
123
|
+
CapacitorUpdaterPlugin.shouldAutoUpdateModeSetNextBundle(normalizedMode),
|
|
124
|
+
try bool(expect, "setNextBundle", id: id),
|
|
125
|
+
id
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
func testOnLaunchDirectUpdateConsumptionMatchesNativeContract() throws {
|
|
131
|
+
for testCase in try contractCases("onLaunchDirectUpdateConsumption") {
|
|
132
|
+
let id = try string(testCase, "id", id: "onLaunchDirectUpdateConsumption")
|
|
133
|
+
let input = try dictionary(testCase, "input", id: id)
|
|
134
|
+
let expect = try dictionary(testCase, "expect", id: id)
|
|
135
|
+
|
|
136
|
+
XCTAssertEqual(
|
|
137
|
+
CapacitorUpdaterPlugin.shouldConsumeOnLaunchDirectUpdate(
|
|
138
|
+
directUpdateMode: try string(input, "mode", id: id),
|
|
139
|
+
plannedDirectUpdate: try bool(input, "plannedDirectUpdate", id: id)
|
|
140
|
+
),
|
|
141
|
+
try bool(expect, "consume", id: id),
|
|
142
|
+
id
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
func testUpdateResponseKindMatchesNativeContract() throws {
|
|
148
|
+
for testCase in try contractCases("updateResponseKind") {
|
|
149
|
+
let id = try string(testCase, "id", id: "updateResponseKind")
|
|
150
|
+
let input = try dictionary(testCase, "input", id: id)
|
|
151
|
+
let expect = try dictionary(testCase, "expect", id: id)
|
|
152
|
+
|
|
153
|
+
XCTAssertEqual(
|
|
154
|
+
CapacitorUpdaterPlugin.normalizedUpdateResponseKind(kind: try optionalString(input, "kind", id: id)),
|
|
155
|
+
try string(expect, "kind", id: id),
|
|
156
|
+
id
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|