@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.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2607 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,280 @@
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
+
9
+ /// Parses the ZIP end of central directory (including ZIP64) and the central directory entries.
10
+ /// Every offset and length is bounds-checked; malformed input throws `ZipError`.
11
+ enum ZipCentralDirectory {
12
+ private static let eocdSignature: UInt32 = 0x0605_4b50
13
+ private static let zip64EocdSignature: UInt32 = 0x0606_4b50
14
+ private static let zip64LocatorSignature: UInt32 = 0x0706_4b50
15
+ private static let entrySignature: UInt32 = 0x0201_4b50
16
+ private static let eocdSize = 22
17
+ private static let zip64LocatorSize = 20
18
+ private static let zip64EocdMinimumSize = 56
19
+ private static let entryMinimumSize = 46
20
+ private static let maxCommentLength = 0xFFFF
21
+ private static let zip64ExtraFieldId: UInt16 = 0x0001
22
+
23
+ private struct EntrySizes {
24
+ var uncompressed: UInt64
25
+ var compressed: UInt64
26
+ var localHeaderOffset: UInt64
27
+ }
28
+
29
+ private struct Location {
30
+ var totalEntries: UInt64
31
+ var size: UInt64
32
+ var offset: UInt64
33
+ /// The central directory must end before this offset (the EOCD or ZIP64 EOCD record).
34
+ var end: UInt64
35
+ }
36
+
37
+ static func readEntries(handle: FileHandle, fileSize: UInt64) throws -> [ZipEntry] {
38
+ let location = try locateCentralDirectory(handle: handle, fileSize: fileSize)
39
+ guard location.offset <= location.end, location.size <= location.end - location.offset else {
40
+ throw ZipError.invalidCentralDirectory
41
+ }
42
+ // Every central directory entry takes at least 46 bytes, which bounds the entry count.
43
+ guard location.totalEntries <= location.size / UInt64(entryMinimumSize), location.size <= UInt64(Int.max) else {
44
+ throw ZipError.invalidCentralDirectory
45
+ }
46
+
47
+ let data = try ZipBytes.readChunk(handle: handle, fileSize: fileSize, at: location.offset, count: Int(location.size))
48
+ var entries: [ZipEntry] = []
49
+ entries.reserveCapacity(Int(location.totalEntries))
50
+ var cursor = 0
51
+ for _ in 0..<location.totalEntries {
52
+ let (entry, next) = try parseEntry(data, at: cursor)
53
+ entries.append(entry)
54
+ cursor = next
55
+ }
56
+ return entries
57
+ }
58
+
59
+ private static func locateCentralDirectory(handle: FileHandle, fileSize: UInt64) throws -> Location {
60
+ guard fileSize >= UInt64(eocdSize) else {
61
+ throw ZipError.missingEndOfCentralDirectory
62
+ }
63
+
64
+ // The EOCD record is at the end of the file, followed by an optional comment of up to 65535 bytes.
65
+ let tailLength = min(fileSize, UInt64(eocdSize + maxCommentLength))
66
+ let tailOffset = fileSize - tailLength
67
+ let tail = try ZipBytes.readChunk(handle: handle, fileSize: fileSize, at: tailOffset, count: Int(tailLength))
68
+
69
+ var eocdIndex: Int?
70
+ var index = tail.count - eocdSize
71
+ while index >= 0 {
72
+ if ZipBytes.uint32(tail, index) == eocdSignature,
73
+ index + eocdSize + Int(ZipBytes.uint16(tail, index + 20)) <= tail.count {
74
+ eocdIndex = index
75
+ break
76
+ }
77
+ index -= 1
78
+ }
79
+ guard let eocdIndex else {
80
+ throw ZipError.missingEndOfCentralDirectory
81
+ }
82
+
83
+ let eocdOffset = tailOffset + UInt64(eocdIndex)
84
+ let location = Location(
85
+ totalEntries: UInt64(ZipBytes.uint16(tail, eocdIndex + 10)),
86
+ size: UInt64(ZipBytes.uint32(tail, eocdIndex + 12)),
87
+ offset: UInt64(ZipBytes.uint32(tail, eocdIndex + 16)),
88
+ end: eocdOffset
89
+ )
90
+ let needsZip64 = location.totalEntries == 0xFFFF || location.size == 0xFFFF_FFFF || location.offset == 0xFFFF_FFFF
91
+ if let zip64Location = try readZip64Location(handle: handle, fileSize: fileSize, eocdOffset: eocdOffset) {
92
+ return zip64Location
93
+ }
94
+ if needsZip64 {
95
+ throw ZipError.invalidCentralDirectory
96
+ }
97
+ return location
98
+ }
99
+
100
+ private static func readZip64Location(handle: FileHandle, fileSize: UInt64, eocdOffset: UInt64) throws -> Location? {
101
+ guard eocdOffset >= UInt64(zip64LocatorSize) else {
102
+ return nil
103
+ }
104
+ let locatorOffset = eocdOffset - UInt64(zip64LocatorSize)
105
+ let locator = try ZipBytes.readChunk(handle: handle, fileSize: fileSize, at: locatorOffset, count: zip64LocatorSize)
106
+ guard ZipBytes.uint32(locator, 0) == zip64LocatorSignature else {
107
+ return nil
108
+ }
109
+ let recordOffset = ZipBytes.uint64(locator, 8)
110
+ guard recordOffset <= locatorOffset, locatorOffset - recordOffset >= UInt64(zip64EocdMinimumSize) else {
111
+ throw ZipError.invalidCentralDirectory
112
+ }
113
+ let record = try ZipBytes.readChunk(handle: handle, fileSize: fileSize, at: recordOffset, count: zip64EocdMinimumSize)
114
+ guard ZipBytes.uint32(record, 0) == zip64EocdSignature else {
115
+ throw ZipError.invalidCentralDirectory
116
+ }
117
+ return Location(
118
+ totalEntries: ZipBytes.uint64(record, 32),
119
+ size: ZipBytes.uint64(record, 40),
120
+ offset: ZipBytes.uint64(record, 48),
121
+ end: recordOffset
122
+ )
123
+ }
124
+
125
+ private static func parseEntry(_ data: Data, at offset: Int) throws -> (ZipEntry, Int) {
126
+ guard offset <= data.count - entryMinimumSize, ZipBytes.uint32(data, offset) == entrySignature else {
127
+ throw ZipError.invalidCentralDirectory
128
+ }
129
+ let versionMadeBy = ZipBytes.uint16(data, offset + 4)
130
+ let flags = ZipBytes.uint16(data, offset + 8)
131
+ let nameLength = Int(ZipBytes.uint16(data, offset + 28))
132
+ let extraLength = Int(ZipBytes.uint16(data, offset + 30))
133
+ let commentLength = Int(ZipBytes.uint16(data, offset + 32))
134
+ let externalAttributes = ZipBytes.uint32(data, offset + 38)
135
+
136
+ let nameStart = offset + entryMinimumSize
137
+ let extraStart = nameStart + nameLength
138
+ let next = extraStart + extraLength + commentLength
139
+ guard next <= data.count else {
140
+ throw ZipError.invalidCentralDirectory
141
+ }
142
+
143
+ var sizes = EntrySizes(
144
+ uncompressed: UInt64(ZipBytes.uint32(data, offset + 24)),
145
+ compressed: UInt64(ZipBytes.uint32(data, offset + 20)),
146
+ localHeaderOffset: UInt64(ZipBytes.uint32(data, offset + 42))
147
+ )
148
+ if sizes.uncompressed == 0xFFFF_FFFF || sizes.compressed == 0xFFFF_FFFF || sizes.localHeaderOffset == 0xFFFF_FFFF {
149
+ sizes = try applyZip64Extra(data, extraRange: extraStart..<(extraStart + extraLength), sizes: sizes)
150
+ }
151
+
152
+ // Same path decoding as ZIPFoundation: UTF-8 when general purpose bit 11 is set, CP437 otherwise.
153
+ let nameData = data.subdata(in: (data.startIndex + nameStart)..<(data.startIndex + extraStart))
154
+ let encoding: String.Encoding = flags & (1 << 11) != 0 ? .utf8 : codePage437
155
+ let path = String(data: nameData, encoding: encoding) ?? ""
156
+
157
+ let entry = ZipEntry(
158
+ path: path,
159
+ type: entryType(path: path, versionMadeBy: versionMadeBy, externalAttributes: externalAttributes),
160
+ generalPurposeFlags: flags,
161
+ compressionMethod: ZipBytes.uint16(data, offset + 10),
162
+ compressedSize: sizes.compressed,
163
+ uncompressedSize: sizes.uncompressed,
164
+ localHeaderOffset: sizes.localHeaderOffset
165
+ )
166
+ return (entry, next)
167
+ }
168
+
169
+ /// ZIP64 extended information: values are present only for fields saturated in the fixed record, in this order.
170
+ private static func applyZip64Extra(
171
+ _ data: Data,
172
+ extraRange: Range<Int>,
173
+ sizes: EntrySizes
174
+ ) throws -> EntrySizes {
175
+ var cursor = extraRange.lowerBound
176
+ while cursor + 4 <= extraRange.upperBound {
177
+ let headerId = ZipBytes.uint16(data, cursor)
178
+ let fieldStart = cursor + 4
179
+ let fieldEnd = fieldStart + Int(ZipBytes.uint16(data, cursor + 2))
180
+ guard fieldEnd <= extraRange.upperBound else {
181
+ throw ZipError.invalidCentralDirectory
182
+ }
183
+ if headerId != zip64ExtraFieldId {
184
+ cursor = fieldEnd
185
+ continue
186
+ }
187
+
188
+ var result = sizes
189
+ var valueCursor = fieldStart
190
+ func nextValue() throws -> UInt64 {
191
+ guard valueCursor + 8 <= fieldEnd else {
192
+ throw ZipError.invalidCentralDirectory
193
+ }
194
+ defer { valueCursor += 8 }
195
+ return ZipBytes.uint64(data, valueCursor)
196
+ }
197
+ if result.uncompressed == 0xFFFF_FFFF {
198
+ result.uncompressed = try nextValue()
199
+ }
200
+ if result.compressed == 0xFFFF_FFFF {
201
+ result.compressed = try nextValue()
202
+ }
203
+ if result.localHeaderOffset == 0xFFFF_FFFF {
204
+ result.localHeaderOffset = try nextValue()
205
+ }
206
+ return result
207
+ }
208
+ throw ZipError.invalidCentralDirectory
209
+ }
210
+
211
+ /// Mirrors ZIPFoundation's `Entry.type` so the same entries are treated as files, directories or symlinks.
212
+ static func entryType(path: String, versionMadeBy: UInt16, externalAttributes: UInt32) -> ZipEntryType {
213
+ let hostSystem = versionMadeBy >> 8
214
+ let hasDirectorySuffix = path.hasSuffix("/")
215
+ switch hostSystem {
216
+ case 3, 19: // UNIX, macOS
217
+ let mode = mode_t(UInt16(truncatingIfNeeded: externalAttributes >> 16)) & S_IFMT
218
+ switch mode {
219
+ case S_IFREG:
220
+ return .file
221
+ case S_IFDIR:
222
+ return .directory
223
+ case S_IFLNK:
224
+ return .symlink
225
+ default:
226
+ return hasDirectorySuffix ? .directory : .file
227
+ }
228
+ case 0: // MS-DOS
229
+ return hasDirectorySuffix || (externalAttributes >> 4) == 0x01 ? .directory : .file
230
+ default:
231
+ return hasDirectorySuffix ? .directory : .file
232
+ }
233
+ }
234
+
235
+ private static let codePage437: String.Encoding = {
236
+ let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.dosLatinUS.rawValue))
237
+ return String.Encoding(rawValue: encoding)
238
+ }()
239
+ }
240
+
241
+ /// Little-endian readers and bounded file reads for ZIP structures.
242
+ enum ZipBytes {
243
+ static func readChunk(handle: FileHandle, fileSize: UInt64, at offset: UInt64, count: Int) throws -> Data {
244
+ guard count >= 0, UInt64(count) <= fileSize, offset <= fileSize - UInt64(count) else {
245
+ throw ZipError.invalidCentralDirectory
246
+ }
247
+ if count == 0 {
248
+ return Data()
249
+ }
250
+ try handle.seek(toOffset: offset)
251
+ guard let data = try handle.read(upToCount: count), data.count == count else {
252
+ throw ZipError.unreadableArchive
253
+ }
254
+ return data
255
+ }
256
+
257
+ // Callers bounds-check `offset` against `data.count` before reading.
258
+ static func uint16(_ data: Data, _ offset: Int) -> UInt16 {
259
+ let base = data.startIndex + offset
260
+ return UInt16(data[base]) | (UInt16(data[base + 1]) << 8)
261
+ }
262
+
263
+ static func uint32(_ data: Data, _ offset: Int) -> UInt32 {
264
+ let base = data.startIndex + offset
265
+ var value: UInt32 = 0
266
+ for byteIndex in 0..<4 {
267
+ value |= UInt32(data[base + byteIndex]) << (8 * UInt32(byteIndex))
268
+ }
269
+ return value
270
+ }
271
+
272
+ static func uint64(_ data: Data, _ offset: Int) -> UInt64 {
273
+ let base = data.startIndex + offset
274
+ var value: UInt64 = 0
275
+ for byteIndex in 0..<8 {
276
+ value |= UInt64(data[base + byteIndex]) << (8 * UInt64(byteIndex))
277
+ }
278
+ return value
279
+ }
280
+ }
@@ -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
+ }