@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
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { registerPlugin } from \"@capacitor/core\";\nconst CapacitorUpdater = registerPlugin(\"CapacitorUpdater\", {\n web: () => import(\"./web\").then((m) => new m.CapacitorUpdaterWeb()),\n});\nexport * from \"./definitions\";\nexport { CapacitorUpdater };\n//# sourceMappingURL=index.js.map","/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { WebPlugin } from \"@capacitor/core\";\nconst BUNDLE_BUILTIN = {\n status: \"success\",\n version: \"\",\n downloaded: \"1970-01-01T00:00:00.000Z\",\n id: \"builtin\",\n checksum: \"\",\n};\nexport class CapacitorUpdaterWeb extends WebPlugin {\n async download(options) {\n console.warn(\"Cannot download version in web\", options);\n return BUNDLE_BUILTIN;\n }\n async next(options) {\n console.warn(\"Cannot set next version in web\", options);\n return BUNDLE_BUILTIN;\n }\n async isAutoUpdateEnabled() {\n console.warn(\"Cannot get isAutoUpdateEnabled in web\");\n return { enabled: false };\n }\n async set(options) {\n console.warn(\"Cannot set active bundle in web\", options);\n return;\n }\n async getDeviceId() {\n console.warn(\"Cannot get ID in web\");\n return { deviceId: \"default\" };\n }\n async getPluginVersion() {\n console.warn(\"Cannot get plugin version in web\");\n return { version: \"default\" };\n }\n async delete(options) {\n console.warn(\"Cannot delete bundle in web\", options);\n }\n async list() {\n console.warn(\"Cannot list bundles in web\");\n return { bundles: [] };\n }\n async reset(options) {\n console.warn(\"Cannot reset version in web\", options);\n }\n async current() {\n console.warn(\"Cannot get current bundle in web\");\n return { bundle: BUNDLE_BUILTIN, native: \"0.0.0\" };\n }\n async reload() {\n console.warn(\"Cannot reload current bundle in web\");\n return;\n }\n async getLatest() {\n console.warn(\"Cannot getLatest current bundle in web\");\n return {\n version: \"0.0.0\",\n message: \"Cannot getLatest current bundle in web\",\n };\n }\n async setChannel(options) {\n console.warn(\"Cannot setChannel in web\", options);\n return {\n status: \"error\",\n error: \"Cannot setChannel in web\",\n };\n }\n async setCustomId(options) {\n console.warn(\"Cannot setCustomId in web\", options);\n return;\n }\n async getChannel() {\n console.warn(\"Cannot getChannel in web\");\n return {\n status: \"error\",\n error: \"Cannot getChannel in web\",\n };\n }\n async notifyAppReady() {\n console.warn(\"Cannot notify App Ready in web\");\n return BUNDLE_BUILTIN;\n }\n async setMultiDelay(options) {\n console.warn(\"Cannot setMultiDelay in web\", options === null || options === void 0 ? void 0 : options.delayConditions);\n return;\n }\n async setDelay(option) {\n console.warn(\"Cannot setDelay in web\", option);\n return;\n }\n async cancelDelay() {\n console.warn(\"Cannot cancelDelay in web\");\n return;\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IAAA;IACA;IACA;IACA;IACA;AAEK,UAAC,gBAAgB,GAAGA,mBAAc,CAAC,kBAAkB,EAAE;IAC5D,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,mBAAmB,EAAE,CAAC;IACvE,CAAC;;ICRD;IACA;IACA;IACA;IACA;IAEA,MAAM,cAAc,GAAG;IACvB,IAAI,MAAM,EAAE,SAAS;IACrB,IAAI,OAAO,EAAE,EAAE;IACf,IAAI,UAAU,EAAE,0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AAY,KAAK,EAAE,0BAA0B;IAC7C,SAAS,CAAC;IACV,KAAK;IACL,IAAI,MAAM,cAAc,GAAG;IAC3B,QAAQ,OAAO,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;IACvD,QAAQ,OAAO,cAAc,CAAC;IAC9B,KAAK;IACL,IAAI,MAAM,aAAa,CAAC,OAAO,EAAE;IACjC,QAAQ,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAC/H,QAAQ,OAAO;IACf,KAAK;IACL,IAAI,MAAM,QAAQ,CAAC,MAAM,EAAE;IAC3B,QAAQ,OAAO,CAAC,IAAI,CAAC,wBAAwB,EAAE,MAAM,CAAC,CAAC;IACvD,QAAQ,OAAO;IACf,KAAK;IACL,IAAI,MAAM,WAAW,GAAG;IACxB,QAAQ,OAAO,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;IAClD,QAAQ,OAAO;IACf,KAAK;IACL;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.js","sources":["esm/history.js","esm/definitions.js","esm/index.js","esm/web.js"],"sourcesContent":["/*\n * Maintains navigation history across Capgo-controlled reloads when keepUrlPathAfterReload is enabled.\n */\nconst KEEP_FLAG_KEY = '__capgo_keep_url_path_after_reload';\nconst HISTORY_STORAGE_KEY = '__capgo_history_stack__';\nconst MAX_STACK_ENTRIES = 100;\nconst isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof history !== 'undefined';\nif (isBrowser) {\n const win = window;\n if (!win.__capgoHistoryPatched) {\n win.__capgoHistoryPatched = true;\n const isFeatureConfigured = () => {\n try {\n if (win.__capgoKeepUrlPathAfterReload) {\n return true;\n }\n }\n catch (_a) {\n // ignore access issues\n }\n try {\n return window.localStorage.getItem(KEEP_FLAG_KEY) === '1';\n }\n catch (_b) {\n return false;\n }\n };\n const readStored = () => {\n try {\n const raw = window.sessionStorage.getItem(HISTORY_STORAGE_KEY);\n if (!raw) {\n return { stack: [], index: -1 };\n }\n const parsed = JSON.parse(raw);\n if (!parsed || !Array.isArray(parsed.stack) || typeof parsed.index !== 'number') {\n return { stack: [], index: -1 };\n }\n return parsed;\n }\n catch (_a) {\n return { stack: [], index: -1 };\n }\n };\n const writeStored = (stack, index) => {\n try {\n window.sessionStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify({ stack, index }));\n }\n catch (_a) {\n // Storage might be unavailable; fail silently.\n }\n };\n const clearStored = () => {\n try {\n window.sessionStorage.removeItem(HISTORY_STORAGE_KEY);\n }\n catch (_a) {\n // ignore\n }\n };\n const normalize = (url) => {\n try {\n const base = url !== null && url !== void 0 ? url : window.location.href;\n const parsed = new URL(base instanceof URL ? base.toString() : base, window.location.href);\n return `${parsed.pathname}${parsed.search}${parsed.hash}`;\n }\n catch (_a) {\n return null;\n }\n };\n const trimStack = (stack, index) => {\n if (stack.length <= MAX_STACK_ENTRIES) {\n return { stack, index };\n }\n const start = stack.length - MAX_STACK_ENTRIES;\n const trimmed = stack.slice(start);\n const adjustedIndex = Math.max(0, index - start);\n return { stack: trimmed, index: adjustedIndex };\n };\n const runWhenReady = (fn) => {\n if (document.readyState === 'complete' || document.readyState === 'interactive') {\n fn();\n }\n else {\n window.addEventListener('DOMContentLoaded', fn, { once: true });\n }\n };\n let featureActive = false;\n let isRestoring = false;\n let restoreScheduled = false;\n const ensureCurrentTracked = () => {\n if (!featureActive) {\n return;\n }\n const stored = readStored();\n const current = normalize();\n if (!current) {\n return;\n }\n if (stored.stack.length === 0) {\n stored.stack.push(current);\n stored.index = 0;\n writeStored(stored.stack, stored.index);\n return;\n }\n if (stored.index < 0 || stored.index >= stored.stack.length) {\n stored.index = stored.stack.length - 1;\n }\n if (stored.stack[stored.index] !== current) {\n stored.stack[stored.index] = current;\n writeStored(stored.stack, stored.index);\n }\n };\n const record = (url, replace) => {\n if (!featureActive || isRestoring) {\n return;\n }\n const normalized = normalize(url);\n if (!normalized) {\n return;\n }\n let { stack, index } = readStored();\n if (stack.length === 0) {\n stack.push(normalized);\n index = stack.length - 1;\n }\n else if (replace) {\n if (index < 0 || index >= stack.length) {\n index = stack.length - 1;\n }\n stack[index] = normalized;\n }\n else {\n if (index >= stack.length - 1) {\n stack.push(normalized);\n index = stack.length - 1;\n }\n else {\n stack = stack.slice(0, index + 1);\n stack.push(normalized);\n index = stack.length - 1;\n }\n }\n ({ stack, index } = trimStack(stack, index));\n writeStored(stack, index);\n };\n const restoreHistory = () => {\n if (!featureActive || isRestoring) {\n return;\n }\n const stored = readStored();\n if (stored.stack.length === 0) {\n ensureCurrentTracked();\n return;\n }\n const targetIndex = stored.index >= 0 && stored.index < stored.stack.length ? stored.index : stored.stack.length - 1;\n const normalizedCurrent = normalize();\n if (stored.stack.length === 1 && normalizedCurrent === stored.stack[0]) {\n return;\n }\n const firstEntry = stored.stack[0];\n if (!firstEntry) {\n return;\n }\n isRestoring = true;\n try {\n history.replaceState(history.state, document.title, firstEntry);\n for (let i = 1; i < stored.stack.length; i += 1) {\n history.pushState(history.state, document.title, stored.stack[i]);\n }\n }\n catch (_a) {\n isRestoring = false;\n return;\n }\n isRestoring = false;\n const currentIndex = stored.stack.length - 1;\n const offset = targetIndex - currentIndex;\n if (offset !== 0) {\n history.go(offset);\n }\n else {\n history.replaceState(history.state, document.title, stored.stack[targetIndex]);\n window.dispatchEvent(new PopStateEvent('popstate'));\n }\n };\n const scheduleRestore = () => {\n if (!featureActive || restoreScheduled) {\n return;\n }\n restoreScheduled = true;\n runWhenReady(() => {\n restoreScheduled = false;\n restoreHistory();\n });\n };\n let originalPushState = null;\n let originalReplaceState = null;\n const popstateHandler = () => {\n if (!featureActive || isRestoring) {\n return;\n }\n const normalized = normalize();\n if (!normalized) {\n return;\n }\n const stored = readStored();\n const idx = stored.stack.lastIndexOf(normalized);\n if (idx >= 0) {\n stored.index = idx;\n }\n else {\n stored.stack.push(normalized);\n stored.index = stored.stack.length - 1;\n }\n const trimmed = trimStack(stored.stack, stored.index);\n writeStored(trimmed.stack, trimmed.index);\n };\n const patchHistory = () => {\n if (originalPushState && originalReplaceState) {\n return;\n }\n originalPushState = history.pushState;\n originalReplaceState = history.replaceState;\n history.pushState = function pushStatePatched(state, title, url) {\n const result = originalPushState === null || originalPushState === void 0 ? void 0 : originalPushState.call(history, state, title, url);\n record(url, false);\n return result;\n };\n history.replaceState = function replaceStatePatched(state, title, url) {\n const result = originalReplaceState === null || originalReplaceState === void 0 ? void 0 : originalReplaceState.call(history, state, title, url);\n record(url, true);\n return result;\n };\n window.addEventListener('popstate', popstateHandler);\n };\n const unpatchHistory = () => {\n if (originalPushState) {\n history.pushState = originalPushState;\n originalPushState = null;\n }\n if (originalReplaceState) {\n history.replaceState = originalReplaceState;\n originalReplaceState = null;\n }\n window.removeEventListener('popstate', popstateHandler);\n };\n const setFeatureActive = (enabled) => {\n if (featureActive === enabled) {\n if (featureActive) {\n ensureCurrentTracked();\n scheduleRestore();\n }\n return;\n }\n featureActive = enabled;\n if (featureActive) {\n patchHistory();\n ensureCurrentTracked();\n scheduleRestore();\n }\n else {\n unpatchHistory();\n clearStored();\n }\n };\n window.addEventListener('CapacitorUpdaterKeepUrlPathAfterReload', (event) => {\n var _a;\n const evt = event;\n const enabled = (_a = evt === null || evt === void 0 ? void 0 : evt.detail) === null || _a === void 0 ? void 0 : _a.enabled;\n if (typeof enabled === 'boolean') {\n win.__capgoKeepUrlPathAfterReload = enabled;\n setFeatureActive(enabled);\n }\n else {\n win.__capgoKeepUrlPathAfterReload = true;\n setFeatureActive(true);\n }\n });\n setFeatureActive(isFeatureConfigured());\n }\n}\nexport {};\n//# sourceMappingURL=history.js.map","/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n/**\n * Update availability status.\n *\n * @since 8.0.0\n */\nexport var AppUpdateAvailability;\n(function (AppUpdateAvailability) {\n /**\n * Update availability is unknown.\n * This typically means the check hasn't completed or failed.\n */\n AppUpdateAvailability[AppUpdateAvailability[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n /**\n * No update is available.\n * The installed version is the latest.\n */\n AppUpdateAvailability[AppUpdateAvailability[\"UPDATE_NOT_AVAILABLE\"] = 1] = \"UPDATE_NOT_AVAILABLE\";\n /**\n * An update is available for download.\n */\n AppUpdateAvailability[AppUpdateAvailability[\"UPDATE_AVAILABLE\"] = 2] = \"UPDATE_AVAILABLE\";\n /**\n * An update is currently being downloaded or installed.\n */\n AppUpdateAvailability[AppUpdateAvailability[\"UPDATE_IN_PROGRESS\"] = 3] = \"UPDATE_IN_PROGRESS\";\n})(AppUpdateAvailability || (AppUpdateAvailability = {}));\n/**\n * Installation status for flexible updates (Android only).\n *\n * @since 8.0.0\n */\nexport var FlexibleUpdateInstallStatus;\n(function (FlexibleUpdateInstallStatus) {\n /**\n * Unknown install status.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n /**\n * Download is pending and will start soon.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"PENDING\"] = 1] = \"PENDING\";\n /**\n * Download is in progress.\n * Check `bytesDownloaded` and `totalBytesToDownload` for progress.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"DOWNLOADING\"] = 2] = \"DOWNLOADING\";\n /**\n * The update is being installed.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"INSTALLING\"] = 3] = \"INSTALLING\";\n /**\n * The update has been installed.\n * The app needs to be restarted to use the new version.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"INSTALLED\"] = 4] = \"INSTALLED\";\n /**\n * The update failed to download or install.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"FAILED\"] = 5] = \"FAILED\";\n /**\n * The update was canceled by the user.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"CANCELED\"] = 6] = \"CANCELED\";\n /**\n * The update has been downloaded and is ready to install.\n * Call {@link CapacitorUpdaterPlugin.completeFlexibleUpdate} to install.\n */\n FlexibleUpdateInstallStatus[FlexibleUpdateInstallStatus[\"DOWNLOADED\"] = 11] = \"DOWNLOADED\";\n})(FlexibleUpdateInstallStatus || (FlexibleUpdateInstallStatus = {}));\n/**\n * Result codes for app update operations.\n *\n * @since 8.0.0\n */\nexport var AppUpdateResultCode;\n(function (AppUpdateResultCode) {\n /**\n * The update completed successfully.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"OK\"] = 0] = \"OK\";\n /**\n * The user canceled the update.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"CANCELED\"] = 1] = \"CANCELED\";\n /**\n * The update failed.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"FAILED\"] = 2] = \"FAILED\";\n /**\n * No update is available.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"NOT_AVAILABLE\"] = 3] = \"NOT_AVAILABLE\";\n /**\n * The requested update type is not allowed.\n * For example, trying to perform an immediate update when only flexible is allowed.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"NOT_ALLOWED\"] = 4] = \"NOT_ALLOWED\";\n /**\n * Required information is missing.\n * This can happen if {@link CapacitorUpdaterPlugin.getAppUpdateInfo} wasn't called first.\n */\n AppUpdateResultCode[AppUpdateResultCode[\"INFO_MISSING\"] = 5] = \"INFO_MISSING\";\n})(AppUpdateResultCode || (AppUpdateResultCode = {}));\n//# sourceMappingURL=definitions.js.map","/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { registerPlugin } from '@capacitor/core';\nimport './history';\nconst CapacitorUpdater = registerPlugin('CapacitorUpdater', {\n web: () => import('./web').then((m) => new m.CapacitorUpdaterWeb()),\n});\nexport * from './definitions';\nexport { CapacitorUpdater };\n//# sourceMappingURL=index.js.map","/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { WebPlugin } from '@capacitor/core';\nimport { AppUpdateAvailability } from './definitions';\nconst BUNDLE_BUILTIN = {\n status: 'success',\n version: '',\n downloaded: '1970-01-01T00:00:00.000Z',\n id: 'builtin',\n checksum: '',\n};\nexport class CapacitorUpdaterWeb extends WebPlugin {\n async setStatsUrl(options) {\n console.warn('Cannot setStatsUrl in web', options);\n return;\n }\n async setUpdateUrl(options) {\n console.warn('Cannot setUpdateUrl in web', options);\n return;\n }\n async setChannelUrl(options) {\n console.warn('Cannot setChannelUrl in web', options);\n return;\n }\n async download(options) {\n console.warn('Cannot download version in web', options);\n return BUNDLE_BUILTIN;\n }\n async next(options) {\n console.warn('Cannot set next version in web', options);\n return BUNDLE_BUILTIN;\n }\n async isAutoUpdateEnabled() {\n console.warn('Cannot get isAutoUpdateEnabled in web');\n return { enabled: false };\n }\n async set(options) {\n console.warn('Cannot set active bundle in web', options);\n return;\n }\n async startPreviewSession(options) {\n console.warn('Cannot start preview session in web', options);\n return;\n }\n async listPreviews() {\n console.warn('Cannot list previews in web');\n return { previews: [], currentBundle: BUNDLE_BUILTIN };\n }\n async setPreview(options) {\n console.warn('Cannot set preview in web', options);\n return;\n }\n async resetPreview() {\n console.warn('Cannot reset preview in web');\n return;\n }\n async deletePreview(options) {\n console.warn('Cannot delete preview in web', options);\n return { removed: false, deleted: false };\n }\n async checkPreviewUpdate(options) {\n console.warn('Cannot check preview update in web', options);\n throw this.unimplemented('Preview updates are not available on web platform');\n }\n async updatePreview(options) {\n console.warn('Cannot update preview in web', options);\n throw this.unimplemented('Preview updates are not available on web platform');\n }\n async getDeviceId() {\n console.warn('Cannot get ID in web');\n return { deviceId: 'default' };\n }\n async getBuiltinVersion() {\n console.warn('Cannot get version in web');\n return { version: 'default' };\n }\n async getPluginVersion() {\n console.warn('Cannot get plugin version in web');\n return { version: 'default' };\n }\n async delete(options) {\n console.warn('Cannot delete bundle in web', options);\n }\n async setBundleError(options) {\n console.warn('Cannot setBundleError in web', options);\n return BUNDLE_BUILTIN;\n }\n async list() {\n console.warn('Cannot list bundles in web');\n return { bundles: [] };\n }\n async reset(options) {\n console.warn('Cannot reset version in web', options);\n }\n async current() {\n console.warn('Cannot get current bundle in web');\n return { bundle: BUNDLE_BUILTIN, native: '0.0.0' };\n }\n async reload() {\n console.warn('Cannot reload current bundle in web');\n return;\n }\n async getLatest() {\n console.warn('Cannot getLatest current bundle in web');\n return {\n version: '0.0.0',\n message: 'Cannot getLatest current bundle in web',\n };\n }\n async triggerUpdateCheck() {\n console.warn('Cannot triggerUpdateCheck in web');\n return { status: 'unavailable', queued: false };\n }\n async getMissingBundleFiles(options) {\n var _a, _b, _c;\n console.warn('Cannot inspect missing bundle files in web', { manifestLength: (_b = (_a = options.manifest) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 });\n const missing = (_c = options.manifest) !== null && _c !== void 0 ? _c : [];\n return {\n missing,\n total: missing.length,\n missingCount: missing.length,\n reusableCount: 0,\n };\n }\n async getBundleDownloadSize(options) {\n var _a, _b, _c, _d, _e;\n console.warn('Cannot estimate bundle download size in web', { manifestLength: (_b = (_a = options.manifest) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0 });\n return {\n totalSize: 0,\n knownFiles: 0,\n unknownFiles: (_d = (_c = options.manifest) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0,\n files: ((_e = options.manifest) !== null && _e !== void 0 ? _e : []).map((entry) => ({\n file_name: entry.file_name,\n file_hash: entry.file_hash,\n download_url: entry.download_url,\n error: 'unavailable',\n })),\n };\n }\n async setChannel(options) {\n console.warn('Cannot setChannel in web', options);\n return {\n status: 'error',\n error: 'Cannot setChannel in web',\n };\n }\n async unsetChannel(options) {\n console.warn('Cannot unsetChannel in web', options);\n return;\n }\n async setCustomId(options) {\n console.warn('Cannot setCustomId in web', options);\n return;\n }\n async getChannel() {\n console.warn('Cannot getChannel in web');\n return {\n status: 'error',\n error: 'Cannot getChannel in web',\n };\n }\n async listChannels() {\n console.warn('Cannot listChannels in web');\n throw {\n message: 'Cannot listChannels in web',\n error: 'platform_not_supported',\n };\n }\n async notifyAppReady() {\n return { bundle: BUNDLE_BUILTIN };\n }\n async setMultiDelay(options) {\n console.warn('Cannot setMultiDelay in web', options === null || options === void 0 ? void 0 : options.delayConditions);\n return;\n }\n async cancelDelay() {\n console.warn('Cannot cancelDelay in web');\n return;\n }\n async isAutoUpdateAvailable() {\n console.warn('Cannot isAutoUpdateAvailable in web');\n return { available: false };\n }\n async getCurrentBundle() {\n console.warn('Cannot get current bundle in web');\n return BUNDLE_BUILTIN;\n }\n async getNextBundle() {\n return Promise.resolve(null);\n }\n async getFailedUpdate() {\n console.warn('Cannot getFailedUpdate in web');\n return null;\n }\n async setShakeMenu(_options) {\n throw this.unimplemented('Shake menu not available on web platform');\n }\n async isShakeMenuEnabled() {\n return Promise.resolve({ enabled: false, gesture: 'shake' });\n }\n async setShakeChannelSelector(_options) {\n throw this.unimplemented('Shake channel selector not available on web platform');\n }\n async isShakeChannelSelectorEnabled() {\n return Promise.resolve({ enabled: false });\n }\n async getAppId() {\n console.warn('Cannot getAppId in web');\n return { appId: 'default' };\n }\n async setAppId(options) {\n console.warn('Cannot setAppId in web', options);\n return;\n }\n // ============================================================================\n // App Store / Play Store Update Methods (Web stubs)\n // ============================================================================\n async getAppUpdateInfo(_options) {\n console.warn('getAppUpdateInfo is not available on web platform');\n return {\n currentVersionName: '0.0.0',\n currentVersionCode: '0',\n updateAvailability: AppUpdateAvailability.UNKNOWN,\n };\n }\n async openAppStore(_options) {\n throw this.unimplemented('openAppStore is not available on web platform');\n }\n async performImmediateUpdate() {\n throw this.unimplemented('performImmediateUpdate is only available on Android');\n }\n async startFlexibleUpdate() {\n throw this.unimplemented('startFlexibleUpdate is only available on Android');\n }\n async completeFlexibleUpdate() {\n throw this.unimplemented('completeFlexibleUpdate is only available on Android');\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["AppUpdateAvailability","FlexibleUpdateInstallStatus","AppUpdateResultCode","registerPlugin","WebPlugin"],"mappings":";;;IAAA;IACA;IACA;IACA,MAAM,aAAa,GAAG,oCAAoC;IAC1D,MAAM,mBAAmB,GAAG,yBAAyB;IACrD,MAAM,iBAAiB,GAAG,GAAG;IAC7B,MAAM,SAAS,GAAG,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW;IACpH,IAAI,SAAS,EAAE;IACf,IAAI,MAAM,GAAG,GAAG,MAAM;IACtB,IAAI,IAAI,CAAC,GAAG,CAAC,qBAAqB,EAAE;IACpC,QAAQ,GAAG,CAAC,qBAAqB,GAAG,IAAI;IACxC,QAAQ,MAAM,mBAAmB,GAAG,MAAM;IAC1C,YAAY,IAAI;IAChB,gBAAgB,IAAI,GAAG,CAAC,6BAA6B,EAAE;IACvD,oBAAoB,OAAO,IAAI;IAC/B,gBAAgB;IAChB,YAAY;IACZ,YAAY,OAAO,EAAE,EAAE;IACvB;IACA,YAAY;IACZ,YAAY,IAAI;IAChB,gBAAgB,OAAO,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,GAAG;IACzE,YAAY;IACZ,YAAY,OAAO,EAAE,EAAE;IACvB,gBAAgB,OAAO,KAAK;IAC5B,YAAY;IACZ,QAAQ,CAAC;IACT,QAAQ,MAAM,UAAU,GAAG,MAAM;IACjC,YAAY,IAAI;IAChB,gBAAgB,MAAM,GAAG,GAAG,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,mBAAmB,CAAC;IAC9E,gBAAgB,IAAI,CAAC,GAAG,EAAE;IAC1B,oBAAoB,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,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I,CAAC,wBAAwB,EAAE,OAAO,CAAC;IACvD,QAAQ;IACR,IAAI;IACJ;IACA;IACA;IACA,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC,QAAQ,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC;IACzE,QAAQ,OAAO;IACf,YAAY,kBAAkB,EAAE,OAAO;IACvC,YAAY,kBAAkB,EAAE,GAAG;IACnC,YAAY,kBAAkB,EAAEJ,6BAAqB,CAAC,OAAO;IAC7D,SAAS;IACT,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,QAAQ,EAAE;IACjC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,+CAA+C,CAAC;IACjF,IAAI;IACJ,IAAI,MAAM,sBAAsB,GAAG;IACnC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,qDAAqD,CAAC;IACvF,IAAI;IACJ,IAAI,MAAM,mBAAmB,GAAG;IAChC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,kDAAkD,CAAC;IACpF,IAAI;IACJ,IAAI,MAAM,sBAAsB,GAAG;IACnC,QAAQ,MAAM,IAAI,CAAC,aAAa,CAAC,qDAAqD,CAAC;IACvF,IAAI;IACJ;;;;;;;;;;;"}
@@ -0,0 +1,262 @@
1
+ import Foundation
2
+ import CommonCrypto
3
+ import CryptoKit
4
+ import Darwin
5
+
6
+ ///
7
+ /// Constants
8
+ ///
9
+ private enum AESConstants {
10
+ static let aesAlgorithm: CCAlgorithm = CCAlgorithm(kCCAlgorithmAES)
11
+ // CommonCrypto's PKCS7 mode accepts corrupted padding and ciphertext that is not block aligned,
12
+ // so decryption runs without padding and PKCS#7 is checked and removed by `strictPkcs7PaddingLength`.
13
+ static let aesOptions: CCOptions = CCOptions(0)
14
+ static let blockSize = kCCBlockSizeAES128
15
+ }
16
+
17
+ /// Returns the PKCS#7 padding length of the final plaintext block, or nil when the padding is invalid.
18
+ func strictPkcs7PaddingLength(lastBlock: [UInt8]) -> Int? {
19
+ guard lastBlock.count == AESConstants.blockSize, let padding = lastBlock.last else {
20
+ return nil
21
+ }
22
+ let length = Int(padding)
23
+ guard length >= 1 && length <= AESConstants.blockSize else {
24
+ return nil
25
+ }
26
+ for byte in lastBlock.suffix(length) where byte != padding {
27
+ return nil
28
+ }
29
+ return length
30
+ }
31
+
32
+ // We do all this stuff because ios is shit and open source libraries allow to do decryption with public key
33
+ // So we have to do it manually, while in nodejs or Java it's ok and done at language level.
34
+
35
+ ///
36
+ /// The AES key. Contains both the initialization vector and secret key.
37
+ ///
38
+ public struct AES128Key {
39
+ /// Initialization vector
40
+ private let initVector: Data
41
+ private let logger: Logger
42
+ private let aes128Key: Data
43
+ #if DEBUG
44
+ // swiftlint:disable:next identifier_name
45
+ public var __debug_iv: Data { initVector }
46
+ // swiftlint:disable:next identifier_name
47
+ public var __debug_aes128Key: Data { aes128Key }
48
+ #endif
49
+ // swiftlint:disable:next identifier_name
50
+ init(iv: Data, aes128Key: Data, logger: Logger) {
51
+ self.initVector = iv
52
+ self.aes128Key = aes128Key
53
+ self.logger = logger
54
+ }
55
+ ///
56
+ /// Takes the data and uses the private key to decrypt it. Will call `CCCrypt` in CommonCrypto
57
+ /// and provide it `ivData` for the initialization vector. Will use cipher block chaining (CBC) as
58
+ /// the mode of operation.
59
+ ///
60
+ /// Returns the decrypted data, or nil when the ciphertext is not block aligned or the PKCS#7 padding is invalid.
61
+ ///
62
+ public func decrypt(data: Data) -> Data? {
63
+ guard let plain = decryptBlocks(data) else {
64
+ return nil
65
+ }
66
+ guard let padding = strictPkcs7PaddingLength(lastBlock: Array(plain.suffix(AESConstants.blockSize))) else {
67
+ logger.error("AES decryption failed: invalid padding")
68
+ return nil
69
+ }
70
+ return plain.prefix(plain.count - padding)
71
+ }
72
+
73
+ /// AES-CBC decryption of whole blocks, padding left in place. Nil when `data` is empty or not block aligned.
74
+ func decryptBlocks(_ data: Data) -> Data? {
75
+ guard !data.isEmpty, data.count % AESConstants.blockSize == 0 else {
76
+ logger.error("AES ciphertext is not block aligned")
77
+ return nil
78
+ }
79
+ var output = [UInt8](repeating: 0, count: data.count)
80
+ var decryptedLength: size_t = 0
81
+ let input = [UInt8](data)
82
+ let keyBytes = [UInt8](aes128Key)
83
+ let ivBytes = [UInt8](initVector)
84
+ let status: CCCryptorStatus = CCCrypt(
85
+ CCOperation(kCCDecrypt),
86
+ AESConstants.aesAlgorithm,
87
+ AESConstants.aesOptions,
88
+ keyBytes,
89
+ keyBytes.count,
90
+ ivBytes,
91
+ input,
92
+ input.count,
93
+ &output,
94
+ output.count,
95
+ &decryptedLength
96
+ )
97
+ guard status == kCCSuccess else {
98
+ logger.error("AES decryption failed with status: \(status)")
99
+ return nil
100
+ }
101
+ return Data(output.prefix(decryptedLength))
102
+ }
103
+
104
+ /// Rejects empty ciphertext and ciphertext that is not a whole number of AES blocks.
105
+ private func requireBlockAlignedCiphertext(at source: URL) throws {
106
+ let attributes = try FileManager.default.attributesOfItem(atPath: source.path)
107
+ let sourceSize = (attributes[.size] as? NSNumber)?.intValue ?? 0
108
+ guard sourceSize > 0, sourceSize % AESConstants.blockSize == 0 else {
109
+ logger.error("AES ciphertext is not block aligned")
110
+ throw NSError(
111
+ domain: "AESDecryptError",
112
+ code: Int(kCCAlignmentError),
113
+ userInfo: [NSLocalizedDescriptionKey: "AES ciphertext is not block aligned"]
114
+ )
115
+ }
116
+ }
117
+
118
+ private func makeDecryptor() throws -> CCCryptorRef {
119
+ var cryptor: CCCryptorRef?
120
+ let createStatus: CCCryptorStatus = aes128Key.withUnsafeBytes { keyBytes in
121
+ initVector.withUnsafeBytes { ivBytes in
122
+ guard let keyPtr = keyBytes.baseAddress, let ivPtr = ivBytes.baseAddress else {
123
+ return CCCryptorStatus(kCCParamError)
124
+ }
125
+ return CCCryptorCreate(
126
+ CCOperation(kCCDecrypt),
127
+ AESConstants.aesAlgorithm,
128
+ AESConstants.aesOptions,
129
+ keyPtr,
130
+ keyBytes.count,
131
+ ivPtr,
132
+ &cryptor
133
+ )
134
+ }
135
+ }
136
+ guard createStatus == kCCSuccess, let cryptor else {
137
+ logger.error("Failed to create AES cryptor")
138
+ throw NSError(domain: "AESDecryptError", code: Int(createStatus), userInfo: nil)
139
+ }
140
+ return cryptor
141
+ }
142
+
143
+ /// AES-CBC file-to-file. Never holds the whole ciphertext in RAM.
144
+ func decrypt(from source: URL, to destination: URL) throws {
145
+ try requireBlockAlignedCiphertext(at: source)
146
+ let cryptor = try makeDecryptor()
147
+ defer {
148
+ CCCryptorRelease(cryptor)
149
+ }
150
+
151
+ guard let input = InputStream(url: source) else {
152
+ throw NSError(domain: "AESDecryptError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to open AES source"])
153
+ }
154
+ input.open()
155
+ defer {
156
+ input.close()
157
+ }
158
+
159
+ let tempURL = destination.deletingLastPathComponent().appendingPathComponent("capgo-aes-\(UUID().uuidString).tmp")
160
+ let fileManager = FileManager.default
161
+ fileManager.createFile(atPath: tempURL.path, contents: nil)
162
+ let output = try FileHandle(forWritingTo: tempURL)
163
+ defer {
164
+ try? output.close()
165
+ try? fileManager.removeItem(at: tempURL)
166
+ }
167
+
168
+ let bufferSize = CryptoCipher.ioBufferBytes()
169
+ let outBufSize = bufferSize + kCCBlockSizeAES128
170
+ var inBuf = [UInt8](repeating: 0, count: bufferSize)
171
+ var outBuf = [UInt8](repeating: 0, count: outBufSize)
172
+ let outFd = output.fileDescriptor
173
+ // The last decrypted block carries the padding, so it is held back until the end.
174
+ var heldBlock: [UInt8] = []
175
+ func emit(count: Int) throws {
176
+ guard count > 0 else {
177
+ return
178
+ }
179
+ if !heldBlock.isEmpty {
180
+ try Self.writeAll(fd: outFd, buffer: &heldBlock, count: heldBlock.count)
181
+ }
182
+ let writeCount = count - AESConstants.blockSize
183
+ if writeCount > 0 {
184
+ try Self.writeAll(fd: outFd, buffer: &outBuf, count: writeCount)
185
+ }
186
+ heldBlock = Array(outBuf[writeCount..<count])
187
+ }
188
+
189
+ while true {
190
+ let readCount = inBuf.withUnsafeMutableBufferPointer { ptr in
191
+ input.read(ptr.baseAddress!, maxLength: ptr.count)
192
+ }
193
+ if readCount == 0 {
194
+ break
195
+ }
196
+ if readCount < 0 {
197
+ throw input.streamError ?? NSError(domain: "AESDecryptError", code: 2, userInfo: [NSLocalizedDescriptionKey: "AES stream read failed"])
198
+ }
199
+ var moved: size_t = 0
200
+ let status: CCCryptorStatus = inBuf.withUnsafeBufferPointer { inRaw in
201
+ outBuf.withUnsafeMutableBytes { outRaw in
202
+ CCCryptorUpdate(
203
+ cryptor,
204
+ inRaw.baseAddress,
205
+ readCount,
206
+ outRaw.baseAddress,
207
+ outBufSize,
208
+ &moved
209
+ )
210
+ }
211
+ }
212
+ guard status == kCCSuccess else {
213
+ logger.error("AES stream update failed")
214
+ throw NSError(domain: "AESDecryptError", code: Int(status), userInfo: nil)
215
+ }
216
+ try emit(count: moved)
217
+ }
218
+
219
+ var moved: size_t = 0
220
+ let finalStatus: CCCryptorStatus = outBuf.withUnsafeMutableBytes { outRaw in
221
+ CCCryptorFinal(cryptor, outRaw.baseAddress, outBufSize, &moved)
222
+ }
223
+ guard finalStatus == kCCSuccess else {
224
+ logger.error("AES stream finalize failed")
225
+ throw NSError(domain: "AESDecryptError", code: Int(finalStatus), userInfo: nil)
226
+ }
227
+ try emit(count: moved)
228
+ guard let padding = strictPkcs7PaddingLength(lastBlock: heldBlock) else {
229
+ logger.error("AES decryption failed: invalid padding")
230
+ throw NSError(domain: "AESDecryptError", code: Int(kCCDecodeError), userInfo: [NSLocalizedDescriptionKey: "Invalid AES padding"])
231
+ }
232
+ try Self.writeAll(fd: outFd, buffer: &heldBlock, count: heldBlock.count - padding)
233
+ try output.close()
234
+
235
+ let decryptedSize = (try fileManager.attributesOfItem(atPath: tempURL.path)[.size] as? NSNumber)?.uint64Value ?? 0
236
+ if decryptedSize == 0 {
237
+ throw NSError(domain: "Empty decrypted data", code: 7, userInfo: nil)
238
+ }
239
+
240
+ do {
241
+ _ = try fileManager.replaceItemAt(destination, withItemAt: tempURL)
242
+ } catch {
243
+ if fileManager.fileExists(atPath: destination.path) {
244
+ throw error
245
+ }
246
+ try fileManager.moveItem(at: tempURL, to: destination)
247
+ }
248
+ }
249
+
250
+ private static func writeAll(fd: Int32, buffer: inout [UInt8], count: Int) throws {
251
+ var offset = 0
252
+ while offset < count {
253
+ let written = buffer.withUnsafeBufferPointer { ptr -> Int in
254
+ Darwin.write(fd, ptr.baseAddress!.advanced(by: offset), count - offset)
255
+ }
256
+ if written <= 0 {
257
+ throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [NSLocalizedDescriptionKey: "AES stream write failed"])
258
+ }
259
+ offset += written
260
+ }
261
+ }
262
+ }
@@ -0,0 +1,82 @@
1
+ import Foundation
2
+
3
+ final class AppHealthTracker {
4
+ private let appSessionIdDefaultsKey = "CapacitorUpdater.appSessionId"
5
+ private let appSessionForegroundDefaultsKey = "CapacitorUpdater.appSessionForeground"
6
+ private let appSessionStartedAtDefaultsKey = "CapacitorUpdater.appSessionStartedAt"
7
+ private let lastReportedUncleanSessionDefaultsKey = "CapacitorUpdater.lastReportedUncleanSessionId"
8
+
9
+ private let implementation: CapgoUpdater
10
+
11
+ init(implementation: CapgoUpdater) {
12
+ self.implementation = implementation
13
+ }
14
+
15
+ static func shouldReportUncleanForegroundExit(
16
+ previousSessionId: String?,
17
+ lastReportedSessionId: String?,
18
+ wasForeground: Bool
19
+ ) -> Bool {
20
+ guard wasForeground, let previousSessionId, !previousSessionId.isEmpty else {
21
+ return false
22
+ }
23
+ return previousSessionId != lastReportedSessionId
24
+ }
25
+
26
+ func reportPreviousUncleanForegroundExit() {
27
+ let defaults = UserDefaults.standard
28
+ let previousSessionId = defaults.string(forKey: appSessionIdDefaultsKey)
29
+ let lastReportedSessionId = defaults.string(forKey: lastReportedUncleanSessionDefaultsKey)
30
+ let wasForeground = defaults.bool(forKey: appSessionForegroundDefaultsKey)
31
+
32
+ guard Self.shouldReportUncleanForegroundExit(
33
+ previousSessionId: previousSessionId,
34
+ lastReportedSessionId: lastReportedSessionId,
35
+ wasForeground: wasForeground
36
+ ), let previousSessionId else {
37
+ return
38
+ }
39
+
40
+ var metadata = [
41
+ "exit_reason": "unclean_foreground_exit",
42
+ "exit_source": "ios_session_marker",
43
+ "previous_session_id": previousSessionId
44
+ ]
45
+ if let sessionStartedAt = defaults.string(forKey: appSessionStartedAtDefaultsKey), !sessionStartedAt.isEmpty {
46
+ metadata["session_started_at"] = sessionStartedAt
47
+ }
48
+
49
+ let current = implementation.getCurrentBundle()
50
+ implementation.sendStats(
51
+ action: "app_crash",
52
+ versionName: current.getVersionName(),
53
+ oldVersionName: "",
54
+ metadata: metadata
55
+ )
56
+ defaults.set(previousSessionId, forKey: lastReportedUncleanSessionDefaultsKey)
57
+ defaults.synchronize()
58
+ }
59
+
60
+ func startSession() {
61
+ let defaults = UserDefaults.standard
62
+ defaults.set(UUID().uuidString, forKey: appSessionIdDefaultsKey)
63
+ defaults.set(true, forKey: appSessionForegroundDefaultsKey)
64
+ defaults.set(String(Int64(Date().timeIntervalSince1970 * 1000)), forKey: appSessionStartedAtDefaultsKey)
65
+ defaults.synchronize()
66
+ }
67
+
68
+ func markForeground(_ isForeground: Bool) {
69
+ UserDefaults.standard.set(isForeground, forKey: appSessionForegroundDefaultsKey)
70
+ UserDefaults.standard.synchronize()
71
+ }
72
+
73
+ func reportMemoryWarning() {
74
+ let current = implementation.getCurrentBundle()
75
+ implementation.sendStats(
76
+ action: "app_memory_warning",
77
+ versionName: current.getVersionName(),
78
+ oldVersionName: "",
79
+ metadata: ["source": "ios_memory_warning"]
80
+ )
81
+ }
82
+ }
@@ -0,0 +1,185 @@
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
+ @objc public class BundleInfo: NSObject, Decodable, Encodable {
10
+ // swiftlint:disable identifier_name
11
+ public static let ID_BUILTIN: String = "builtin"
12
+ public static let VERSION_UNKNOWN: String = "unknown"
13
+ public static let DOWNLOADED_BUILTIN: String = "1970-01-01T00:00:00.000Z"
14
+ // swiftlint:enable identifier_name
15
+
16
+ private let downloaded: String
17
+ private let id: String
18
+ private let version: String
19
+ private let checksum: String
20
+ private let status: BundleStatus
21
+ private let link: String?
22
+ private let comment: String?
23
+
24
+ convenience init(
25
+ id: String, version: String, status: BundleStatus, downloaded: Date,
26
+ checksum: String, link: String? = nil, comment: String? = nil
27
+ ) {
28
+ self.init(
29
+ id: id, version: version, status: status,
30
+ downloaded: downloaded.iso8601withFractionalSeconds,
31
+ checksum: checksum, link: link, comment: comment)
32
+ }
33
+
34
+ init(
35
+ id: String, version: String, status: BundleStatus,
36
+ downloaded: String = BundleInfo.DOWNLOADED_BUILTIN, checksum: String,
37
+ link: String? = nil, comment: String? = nil
38
+ ) {
39
+ self.downloaded = downloaded.trim()
40
+ self.id = id
41
+ self.version = version
42
+ self.checksum = checksum
43
+ self.status = status
44
+ self.link = link
45
+ self.comment = comment
46
+ }
47
+
48
+ enum CodingKeys: String, CodingKey {
49
+ case downloaded, id, version, status, checksum, link, comment
50
+ }
51
+
52
+ public func isBuiltin() -> Bool {
53
+ return BundleInfo.ID_BUILTIN == self.id
54
+ }
55
+
56
+ public func isUnknown() -> Bool {
57
+ return BundleInfo.VERSION_UNKNOWN == self.id
58
+ }
59
+
60
+ public func isErrorStatus() -> Bool {
61
+ return BundleStatus.ERROR == self.status
62
+ }
63
+
64
+ public func isDeleted() -> Bool {
65
+ return BundleStatus.DELETED == self.status
66
+ }
67
+
68
+ public func isDeleting() -> Bool {
69
+ return BundleStatus.DELETING == self.status
70
+ }
71
+
72
+ public func isDownloading() -> Bool {
73
+ return BundleStatus.DOWNLOADING == self.status
74
+ }
75
+
76
+ public func isDownloaded() -> Bool {
77
+ return !self.isBuiltin() && self.downloaded != "" &&
78
+ self.downloaded != BundleInfo.DOWNLOADED_BUILTIN && !self.isDeleted() && !self.isDeleting()
79
+ }
80
+
81
+ public func getDownloaded() -> String {
82
+ return self.isBuiltin() ? BundleInfo.DOWNLOADED_BUILTIN : self.downloaded
83
+ }
84
+
85
+ public func getChecksum() -> String {
86
+ return self.isBuiltin() ? "" : self.checksum
87
+ }
88
+
89
+ public func setChecksum(checksum: String) -> BundleInfo {
90
+ return BundleInfo(
91
+ id: self.id, version: self.version, status: self.status,
92
+ downloaded: self.downloaded, checksum: checksum,
93
+ link: self.link, comment: self.comment)
94
+ }
95
+
96
+ public func setDownloaded(downloaded: Date) -> BundleInfo {
97
+ return BundleInfo(
98
+ id: self.id, version: self.version, status: self.status,
99
+ downloaded: downloaded, checksum: self.checksum,
100
+ link: self.link, comment: self.comment)
101
+ }
102
+
103
+ public func getId() -> String {
104
+ return self.isBuiltin() ? BundleInfo.ID_BUILTIN : self.id
105
+ }
106
+
107
+ public func setId(id: String) -> BundleInfo {
108
+ return BundleInfo(
109
+ id: id, version: self.version, status: self.status,
110
+ downloaded: self.downloaded, checksum: self.checksum,
111
+ link: self.link, comment: self.comment)
112
+ }
113
+
114
+ public func getVersionName() -> String {
115
+ return self.version.isEmpty ? BundleInfo.ID_BUILTIN : self.version
116
+ }
117
+
118
+ public func setVersionName(version: String) -> BundleInfo {
119
+ return BundleInfo(
120
+ id: self.id, version: version, status: self.status,
121
+ downloaded: self.downloaded, checksum: self.checksum,
122
+ link: self.link, comment: self.comment)
123
+ }
124
+
125
+ public func getStatus() -> String {
126
+ return self.isBuiltin() ?
127
+ BundleStatus.SUCCESS.storedValue : self.status.storedValue
128
+ }
129
+
130
+ public func setStatus(status: String) -> BundleInfo {
131
+ return BundleInfo(
132
+ id: self.id, version: self.version,
133
+ status: BundleStatus(storedValue: status)!,
134
+ downloaded: self.downloaded, checksum: self.checksum,
135
+ link: self.link, comment: self.comment)
136
+ }
137
+
138
+ public func getLink() -> String? {
139
+ return self.link
140
+ }
141
+
142
+ public func setLink(link: String?) -> BundleInfo {
143
+ return BundleInfo(
144
+ id: self.id, version: self.version, status: self.status,
145
+ downloaded: self.downloaded, checksum: self.checksum,
146
+ link: link, comment: self.comment)
147
+ }
148
+
149
+ public func getComment() -> String? {
150
+ return self.comment
151
+ }
152
+
153
+ public func setComment(comment: String?) -> BundleInfo {
154
+ return BundleInfo(
155
+ id: self.id, version: self.version, status: self.status,
156
+ downloaded: self.downloaded, checksum: self.checksum,
157
+ link: self.link, comment: comment)
158
+ }
159
+
160
+ public func toJSON() -> [String: String] {
161
+ var result: [String: String] = [
162
+ "id": self.getId(),
163
+ "version": self.getVersionName(),
164
+ "downloaded": self.getDownloaded(),
165
+ "checksum": self.getChecksum(),
166
+ "status": self.getStatus()
167
+ ]
168
+ if let link = self.link {
169
+ result["link"] = link
170
+ }
171
+ if let comment = self.comment {
172
+ result["comment"] = comment
173
+ }
174
+ return result
175
+ }
176
+
177
+ public static func == (lhs: BundleInfo, rhs: BundleInfo) -> Bool {
178
+ return lhs.getVersionName() == rhs.getVersionName()
179
+ }
180
+
181
+ public func toString() -> String {
182
+ // swiftlint:disable:next line_length
183
+ return "{ \"id\": \"\(self.getId())\", \"version\": \"\(self.getVersionName())\", \"downloaded\": \"\(self.getDownloaded())\", \"checksum\": \"\(self.getChecksum())\", \"status\": \"\(self.getStatus())\"}"
184
+ }
185
+ }