@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
@@ -34,9 +34,7 @@ extension UserDefaults: ObjectSavable {
34
34
  }
35
35
 
36
36
  func getObj<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable {
37
- // print("forKey", forKey)
38
37
  guard let data: Data = data(forKey: forKey) else { throw ObjectSavableError.noValue }
39
- // print("data", data)
40
38
  let decoder: JSONDecoder = JSONDecoder()
41
39
  do {
42
40
  let object: Object = try decoder.decode(type, from: data)
@@ -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,304 @@
1
+ import Capacitor
2
+ import Foundation
3
+ import WebKit
4
+
5
+ final class WebViewStatsReporter {
6
+ static let script = """
7
+ (function(){
8
+ if(window.__capgoWebViewErrorReporterInstalled){return;}
9
+ window.__capgoWebViewErrorReporterInstalled=true;
10
+ var maxReports=20,sentReports=0,queue=[],seen={};
11
+ var sessionKey='CapacitorUpdater.webViewSession';
12
+ var sessionId=String(Date.now())+'-'+Math.random().toString(36).slice(2);
13
+ function s(value){
14
+ try{
15
+ if(value===undefined){return '';}
16
+ if(value===null){return 'null';}
17
+ if(typeof value==='string'){return value;}
18
+ if(value&&typeof value.message==='string'){return value.message;}
19
+ return String(value);
20
+ }catch(_){return '';}
21
+ }
22
+ function stack(value){
23
+ try{return value&&value.stack?String(value.stack):'';}catch(_){return '';}
24
+ }
25
+ function updater(){
26
+ var cap=window.Capacitor;
27
+ if(!cap||!cap.Plugins){return null;}
28
+ return cap.Plugins.CapacitorUpdater||null;
29
+ }
30
+ function flush(){
31
+ var plugin=updater();
32
+ if(!plugin||typeof plugin.reportWebViewError!=='function'){return false;}
33
+ while(queue.length){
34
+ var payload=queue.shift();
35
+ try{
36
+ var result=plugin.reportWebViewError(payload);
37
+ if(result&&typeof result.catch==='function'){result.catch(function(){});}
38
+ }catch(_){}
39
+ }
40
+ return true;
41
+ }
42
+ var retries=0;
43
+ function scheduleFlush(){
44
+ if(flush()){return;}
45
+ if(retries++<40){setTimeout(scheduleFlush,250);}
46
+ }
47
+ function send(payload){
48
+ try{
49
+ if(sentReports>=maxReports){return;}
50
+ payload.href=payload.href||location.href||'';
51
+ payload.user_agent=navigator.userAgent||'';
52
+ payload.session_id=sessionId;
53
+ var key=[payload.type,payload.message,payload.source,payload.line,payload.column,payload.tag_name].join('|');
54
+ if(seen[key]){return;}
55
+ seen[key]=true;
56
+ sentReports+=1;
57
+ queue.push(payload);
58
+ scheduleFlush();
59
+ }catch(_){}
60
+ }
61
+ function readSession(){
62
+ try{return JSON.parse(localStorage.getItem(sessionKey)||'null')||null;}catch(_){return null;}
63
+ }
64
+ function writeSession(active){
65
+ try{
66
+ localStorage.setItem(sessionKey,JSON.stringify({
67
+ id:sessionId,
68
+ active:active,
69
+ href:location.href||'',
70
+ started_at:window.__capgoWebViewSessionStartedAt,
71
+ updated_at:String(Date.now())
72
+ }));
73
+ }catch(_){}
74
+ }
75
+ window.__capgoWebViewSessionStartedAt=String(Date.now());
76
+ var previous=readSession();
77
+ if(previous&&previous.active){
78
+ send({
79
+ type:'webview_unclean_restart',
80
+ message:'WebView restarted without a clean page unload',
81
+ previous_session_id:s(previous.id),
82
+ previous_href:s(previous.href),
83
+ previous_started_at:s(previous.started_at),
84
+ previous_updated_at:s(previous.updated_at)
85
+ });
86
+ }
87
+ writeSession(true);
88
+ setInterval(function(){writeSession(true);},15000);
89
+ function pageDuration(){
90
+ var started=Number(window.__capgoWebViewSessionStartedAt||Date.now());
91
+ return String(Math.max(0,Date.now()-started));
92
+ }
93
+ function markClean(){writeSession(false);}
94
+ window.addEventListener('pagehide',markClean,true);
95
+ window.addEventListener('beforeunload',markClean,true);
96
+ window.addEventListener('error',function(event){
97
+ var target=event&&event.target;
98
+ if(target&&target!==window&&(target.src||target.href)){
99
+ send({
100
+ type:'resource_error',
101
+ message:'Resource failed to load',
102
+ source:s(target.src||target.href),
103
+ tag_name:s(target.tagName)
104
+ });
105
+ return;
106
+ }
107
+ send({
108
+ type:'javascript_error',
109
+ message:s((event&&event.message)||(event&&event.error)),
110
+ source:s(event&&event.filename),
111
+ line:s(event&&event.lineno),
112
+ column:s(event&&event.colno),
113
+ stack:stack(event&&event.error)
114
+ });
115
+ },true);
116
+ window.addEventListener('unhandledrejection',function(event){
117
+ var reason=event&&event.reason;
118
+ send({type:'unhandled_rejection',message:s(reason),stack:stack(reason)});
119
+ },true);
120
+ document.addEventListener('securitypolicyviolation',function(event){
121
+ send({
122
+ type:'security_policy_violation',
123
+ message:s(event&&event.violatedDirective),
124
+ source:s(event&&event.blockedURI)
125
+ });
126
+ },true);
127
+ document.addEventListener('DOMContentLoaded',function(){
128
+ send({
129
+ type:'webview_dom_content_loaded',
130
+ message:'WebView DOM content loaded',
131
+ duration_ms:pageDuration(),
132
+ page_started_at:String(window.__capgoWebViewSessionStartedAt)
133
+ });
134
+ },true);
135
+ window.addEventListener('load',function(){
136
+ send({
137
+ type:'webview_page_loaded',
138
+ message:'WebView page loaded',
139
+ duration_ms:pageDuration(),
140
+ page_started_at:String(window.__capgoWebViewSessionStartedAt)
141
+ });
142
+ },true);
143
+ document.addEventListener('deviceready',scheduleFlush,false);
144
+ setTimeout(scheduleFlush,0);
145
+ })();
146
+ """
147
+
148
+ private let implementation: CapgoUpdater
149
+ private var installed = false
150
+
151
+ init(implementation: CapgoUpdater) {
152
+ self.implementation = implementation
153
+ }
154
+
155
+ func install(on webView: WKWebView?) {
156
+ guard !installed else {
157
+ return
158
+ }
159
+ guard let webView else {
160
+ return
161
+ }
162
+
163
+ installed = true
164
+ let userScript = WKUserScript(source: Self.script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
165
+ webView.configuration.userContentController.addUserScript(userScript)
166
+ webView.evaluateJavaScript(Self.script, completionHandler: nil)
167
+ }
168
+
169
+ func reportError(_ call: CAPPluginCall) {
170
+ let errorType = call.getString("type") ?? "javascript_error"
171
+ let current = implementation.getCurrentBundle()
172
+ implementation.sendStats(
173
+ action: Self.statsAction(for: errorType),
174
+ versionName: current.getVersionName(),
175
+ oldVersionName: "",
176
+ metadata: Self.buildMetadata([
177
+ "type": errorType,
178
+ "message": call.getString("message"),
179
+ "source": call.getString("source"),
180
+ "line": call.getString("line") ?? call.getString("lineno"),
181
+ "column": call.getString("column") ?? call.getString("colno"),
182
+ "stack": call.getString("stack"),
183
+ "tag_name": call.getString("tag_name"),
184
+ "href": call.getString("href"),
185
+ "user_agent": call.getString("user_agent"),
186
+ "session_id": call.getString("session_id"),
187
+ "duration_ms": call.getString("duration_ms"),
188
+ "page_started_at": call.getString("page_started_at"),
189
+ "previous_session_id": call.getString("previous_session_id"),
190
+ "previous_href": call.getString("previous_href"),
191
+ "previous_started_at": call.getString("previous_started_at"),
192
+ "previous_updated_at": call.getString("previous_updated_at")
193
+ ])
194
+ )
195
+ call.resolve()
196
+ }
197
+
198
+ static func statsAction(for type: String) -> String {
199
+ switch type {
200
+ case "unhandled_rejection":
201
+ return "webview_unhandled_rejection"
202
+ case "resource_error":
203
+ return "webview_resource_error"
204
+ case "security_policy_violation":
205
+ return "webview_security_policy_violation"
206
+ case "webview_unclean_restart":
207
+ return "webview_unclean_restart"
208
+ case "render_process_gone":
209
+ return "webview_render_process_gone"
210
+ case "web_content_process_terminated":
211
+ return "webview_content_process_terminated"
212
+ case "webview_dom_content_loaded":
213
+ return "webview_dom_content_loaded"
214
+ case "webview_page_loaded":
215
+ return "webview_page_loaded"
216
+ case "javascript_error":
217
+ return "webview_javascript_error"
218
+ default:
219
+ return "webview_javascript_error"
220
+ }
221
+ }
222
+
223
+ static func buildMetadata(_ values: [String: String?]) -> [String: String] {
224
+ var metadata: [String: String] = [:]
225
+ put(&metadata, key: "error_type", value: payloadValue(values, "type") ?? "javascript_error", maxLength: 64)
226
+ put(&metadata, key: "message", value: payloadValue(values, "message"), maxLength: 1_024)
227
+ put(&metadata, key: "source", value: sanitizeUrl(payloadValue(values, "source")), maxLength: 512)
228
+ put(&metadata, key: "line", value: payloadValue(values, "line"), maxLength: 32)
229
+ put(&metadata, key: "column", value: payloadValue(values, "column"), maxLength: 32)
230
+ put(&metadata, key: "stack", value: payloadValue(values, "stack"), maxLength: 2_048)
231
+ put(&metadata, key: "tag_name", value: payloadValue(values, "tag_name"), maxLength: 64)
232
+ put(&metadata, key: "href", value: sanitizeUrl(payloadValue(values, "href")), maxLength: 512)
233
+ put(&metadata, key: "user_agent", value: payloadValue(values, "user_agent"), maxLength: 256)
234
+ put(&metadata, key: "session_id", value: payloadValue(values, "session_id"), maxLength: 128)
235
+ put(&metadata, key: "duration_ms", value: payloadValue(values, "duration_ms"), maxLength: 32)
236
+ put(&metadata, key: "page_started_at", value: payloadValue(values, "page_started_at"), maxLength: 64)
237
+ put(&metadata, key: "previous_session_id", value: payloadValue(values, "previous_session_id"), maxLength: 128)
238
+ put(&metadata, key: "previous_href", value: sanitizeUrl(payloadValue(values, "previous_href")), maxLength: 512)
239
+ put(&metadata, key: "previous_started_at", value: payloadValue(values, "previous_started_at"), maxLength: 64)
240
+ put(&metadata, key: "previous_updated_at", value: payloadValue(values, "previous_updated_at"), maxLength: 64)
241
+ return metadata
242
+ }
243
+
244
+ private static func payloadValue(_ values: [String: String?], _ key: String) -> String? {
245
+ guard let value = values[key] else {
246
+ return nil
247
+ }
248
+ return value
249
+ }
250
+
251
+ static func sanitizeUrl(_ value: String?) -> String? {
252
+ guard let value = value, !value.isEmpty else {
253
+ return value
254
+ }
255
+
256
+ if var components = URLComponents(string: value), components.scheme != nil, components.host != nil {
257
+ components.user = nil
258
+ components.password = nil
259
+ components.query = nil
260
+ components.fragment = nil
261
+ components.path = sanitizeUrlPath(components.path)
262
+ return components.string ?? stripUrlQueryAndFragment(value)
263
+ }
264
+
265
+ return stripUrlQueryAndFragment(value)
266
+ }
267
+
268
+ private static func sanitizeUrlPath(_ path: String) -> String {
269
+ guard !path.isEmpty else {
270
+ return path
271
+ }
272
+
273
+ return path
274
+ .split(separator: "/", omittingEmptySubsequences: false)
275
+ .map { isSensitiveUrlPathSegment(String($0)) ? "redacted" : String($0) }
276
+ .joined(separator: "/")
277
+ }
278
+
279
+ private static func isSensitiveUrlPathSegment(_ segment: String) -> Bool {
280
+ segment.range(of: #"^[0-9]{6,}$"#, options: .regularExpression) != nil ||
281
+ segment.range(of: #"^[0-9a-fA-F]{16,}$"#, options: .regularExpression) != nil ||
282
+ segment.range(
283
+ of: #"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"#,
284
+ options: .regularExpression
285
+ ) != nil
286
+ }
287
+
288
+ private static func stripUrlQueryAndFragment(_ value: String) -> String {
289
+ let queryIndex = value.firstIndex(of: "?")
290
+ let fragmentIndex = value.firstIndex(of: "#")
291
+ let endIndexes = [queryIndex, fragmentIndex].compactMap { $0 }
292
+ guard let endIndex = endIndexes.min() else {
293
+ return value
294
+ }
295
+ return String(value[..<endIndex])
296
+ }
297
+
298
+ private static func put(_ metadata: inout [String: String], key: String, value: String?, maxLength: Int) {
299
+ guard let value = value, !value.isEmpty else {
300
+ return
301
+ }
302
+ metadata[key] = String(value.prefix(maxLength))
303
+ }
304
+ }
@@ -0,0 +1,247 @@
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 Compression
8
+ import Foundation
9
+
10
+ enum ZipError: Error, Equatable {
11
+ case unreadableArchive
12
+ case missingEndOfCentralDirectory
13
+ case invalidCentralDirectory
14
+ case invalidLocalFileHeader
15
+ case truncatedEntryData
16
+ case corruptedEntryData
17
+ case encryptedEntry
18
+ case unsupportedCompressionMethod(UInt16)
19
+ case invalidBufferSize
20
+ case entryTooLarge
21
+ }
22
+
23
+ enum ZipEntryType {
24
+ case file
25
+ case directory
26
+ case symlink
27
+ }
28
+
29
+ struct ZipEntry {
30
+ let path: String
31
+ let type: ZipEntryType
32
+ let generalPurposeFlags: UInt16
33
+ let compressionMethod: UInt16
34
+ let compressedSize: UInt64
35
+ let uncompressedSize: UInt64
36
+ let localHeaderOffset: UInt64
37
+
38
+ var isEncrypted: Bool {
39
+ return generalPurposeFlags & 0x0001 != 0
40
+ }
41
+ }
42
+
43
+ /// Small read-only ZIP reader used to extract downloaded bundles.
44
+ ///
45
+ /// Supports stored (0) and deflate (8) entries, ZIP64 archives, and streams entry contents in
46
+ /// `bufferSize` chunks so large files are never fully loaded in memory. Encrypted entries and other
47
+ /// compression methods are rejected. Every offset and size read from the archive is bounds-checked, so a
48
+ /// corrupt archive throws instead of crashing.
49
+ ///
50
+ /// This reader does not validate entry paths. Callers must resolve `ZipEntry.path` against the destination
51
+ /// directory (see `CapgoUpdater.resolvePathInsideDirectory`) before writing anything.
52
+ final class ZipArchiveReader {
53
+ static let compressionMethodStored: UInt16 = 0
54
+ static let compressionMethodDeflate: UInt16 = 8
55
+ private static let localFileHeaderSignature: UInt32 = 0x0403_4b50
56
+ private static let localFileHeaderSize = 30
57
+
58
+ let entries: [ZipEntry]
59
+ private let fileHandle: FileHandle
60
+ private let fileSize: UInt64
61
+
62
+ init(url: URL) throws {
63
+ let handle: FileHandle
64
+ do {
65
+ handle = try FileHandle(forReadingFrom: url)
66
+ } catch {
67
+ throw ZipError.unreadableArchive
68
+ }
69
+ do {
70
+ let size = try handle.seekToEnd()
71
+ self.fileHandle = handle
72
+ self.fileSize = size
73
+ self.entries = try ZipCentralDirectory.readEntries(handle: handle, fileSize: size)
74
+ } catch {
75
+ try? handle.close()
76
+ throw error
77
+ }
78
+ }
79
+
80
+ deinit {
81
+ try? fileHandle.close()
82
+ }
83
+
84
+ /// Streams the uncompressed contents of `entry` to `consumer` in chunks of at most `bufferSize` bytes.
85
+ /// Directory entries produce no data.
86
+ func extract(_ entry: ZipEntry, bufferSize: Int, consumer: (Data) throws -> Void) throws {
87
+ guard bufferSize > 0 else {
88
+ throw ZipError.invalidBufferSize
89
+ }
90
+ if entry.type == .directory {
91
+ return
92
+ }
93
+ if entry.isEncrypted {
94
+ throw ZipError.encryptedEntry
95
+ }
96
+
97
+ let header = try ZipBytes.readChunk(handle: fileHandle, fileSize: fileSize, at: entry.localHeaderOffset, count: Self.localFileHeaderSize)
98
+ guard ZipBytes.uint32(header, 0) == Self.localFileHeaderSignature else {
99
+ throw ZipError.invalidLocalFileHeader
100
+ }
101
+ let localFlags = ZipBytes.uint16(header, 6)
102
+ let localMethod = ZipBytes.uint16(header, 8)
103
+ let nameLength = UInt64(ZipBytes.uint16(header, 26))
104
+ let extraLength = UInt64(ZipBytes.uint16(header, 28))
105
+ if localFlags & 0x0001 != 0 {
106
+ throw ZipError.encryptedEntry
107
+ }
108
+
109
+ let headerLength = UInt64(Self.localFileHeaderSize) + nameLength + extraLength
110
+ let (dataOffset, overflow) = entry.localHeaderOffset.addingReportingOverflow(headerLength)
111
+ guard !overflow, dataOffset <= fileSize else {
112
+ throw ZipError.invalidLocalFileHeader
113
+ }
114
+
115
+ // Like the previous ZIPFoundation-based extraction, the local header decides the compression method
116
+ // while sizes come from the central directory.
117
+ switch localMethod {
118
+ case Self.compressionMethodStored:
119
+ // A stored entry's payload is its content; a size mismatch would read past it into the next records.
120
+ guard entry.compressedSize == entry.uncompressedSize else {
121
+ throw ZipError.corruptedEntryData
122
+ }
123
+ try readStored(from: dataOffset, size: entry.uncompressedSize, bufferSize: bufferSize, consumer: consumer)
124
+ case Self.compressionMethodDeflate:
125
+ if entry.compressedSize == 0 && entry.uncompressedSize == 0 {
126
+ // Some writers store empty files as deflate with no payload at all.
127
+ return
128
+ }
129
+ try readDeflated(
130
+ from: dataOffset,
131
+ compressedSize: entry.compressedSize,
132
+ expectedSize: entry.uncompressedSize,
133
+ bufferSize: bufferSize,
134
+ consumer: consumer
135
+ )
136
+ default:
137
+ throw ZipError.unsupportedCompressionMethod(localMethod)
138
+ }
139
+ }
140
+
141
+ /// Reads the full contents of a small entry (e.g. a symlink target), refusing entries larger than `maxBytes`.
142
+ func readSmallEntry(_ entry: ZipEntry, maxBytes: Int, bufferSize: Int) throws -> Data {
143
+ var result = Data()
144
+ try extract(entry, bufferSize: bufferSize) { chunk in
145
+ guard result.count + chunk.count <= maxBytes else {
146
+ throw ZipError.entryTooLarge
147
+ }
148
+ result.append(chunk)
149
+ }
150
+ return result
151
+ }
152
+
153
+ private func readStored(from offset: UInt64, size: UInt64, bufferSize: Int, consumer: (Data) throws -> Void) throws {
154
+ guard size <= fileSize, offset <= fileSize - size else {
155
+ throw ZipError.truncatedEntryData
156
+ }
157
+ try fileHandle.seek(toOffset: offset)
158
+ var remaining = size
159
+ while remaining > 0 {
160
+ let chunkSize = Int(min(UInt64(bufferSize), remaining))
161
+ try autoreleasepool {
162
+ guard let chunk = try fileHandle.read(upToCount: chunkSize), chunk.count == chunkSize else {
163
+ throw ZipError.truncatedEntryData
164
+ }
165
+ try consumer(chunk)
166
+ }
167
+ remaining -= UInt64(chunkSize)
168
+ }
169
+ }
170
+
171
+ /// Inflates an entry, rejecting output that differs from the central directory's uncompressed size.
172
+ /// This also bounds decompression bombs to the declared size.
173
+ private func readDeflated(
174
+ from offset: UInt64,
175
+ compressedSize: UInt64,
176
+ expectedSize: UInt64,
177
+ bufferSize: Int,
178
+ consumer: (Data) throws -> Void
179
+ ) throws {
180
+ guard compressedSize <= fileSize, offset <= fileSize - compressedSize else {
181
+ throw ZipError.truncatedEntryData
182
+ }
183
+ try fileHandle.seek(toOffset: offset)
184
+
185
+ let stream = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
186
+ defer { stream.deallocate() }
187
+ // COMPRESSION_ZLIB decodes raw DEFLATE (RFC 1951), which is what ZIP method 8 stores.
188
+ guard compression_stream_init(stream, COMPRESSION_STREAM_DECODE, COMPRESSION_ZLIB) == COMPRESSION_STATUS_OK else {
189
+ throw ZipError.corruptedEntryData
190
+ }
191
+ defer { compression_stream_destroy(stream) }
192
+
193
+ let sourceBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
194
+ defer { sourceBuffer.deallocate() }
195
+ let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
196
+ defer { destinationBuffer.deallocate() }
197
+
198
+ var remaining = compressedSize
199
+ stream.pointee.src_ptr = UnsafePointer(sourceBuffer)
200
+ stream.pointee.src_size = 0
201
+
202
+ var producedTotal: UInt64 = 0
203
+ var finished = false
204
+ while !finished {
205
+ try autoreleasepool {
206
+ if stream.pointee.src_size == 0 && remaining > 0 {
207
+ let chunkSize = Int(min(UInt64(bufferSize), remaining))
208
+ guard let chunk = try fileHandle.read(upToCount: chunkSize), chunk.count == chunkSize else {
209
+ throw ZipError.truncatedEntryData
210
+ }
211
+ chunk.copyBytes(to: sourceBuffer, count: chunkSize)
212
+ stream.pointee.src_ptr = UnsafePointer(sourceBuffer)
213
+ stream.pointee.src_size = chunkSize
214
+ remaining -= UInt64(chunkSize)
215
+ }
216
+
217
+ stream.pointee.dst_ptr = destinationBuffer
218
+ stream.pointee.dst_size = bufferSize
219
+ let flags = remaining == 0 ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0
220
+ let status = compression_stream_process(stream, flags)
221
+ let produced = bufferSize - stream.pointee.dst_size
222
+ if produced > 0 {
223
+ producedTotal += UInt64(produced)
224
+ guard producedTotal <= expectedSize else {
225
+ throw ZipError.corruptedEntryData
226
+ }
227
+ try consumer(Data(bytes: destinationBuffer, count: produced))
228
+ }
229
+
230
+ switch status {
231
+ case COMPRESSION_STATUS_END:
232
+ guard producedTotal == expectedSize else {
233
+ throw ZipError.corruptedEntryData
234
+ }
235
+ finished = true
236
+ case COMPRESSION_STATUS_OK:
237
+ // All input consumed and no output produced: the deflate stream is truncated.
238
+ if remaining == 0 && stream.pointee.src_size == 0 && produced == 0 {
239
+ throw ZipError.truncatedEntryData
240
+ }
241
+ default:
242
+ throw ZipError.corruptedEntryData
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }