native-update-capacitor 0.0.0-stage → 4.4.0

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 (140) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/flutter-patch.js +107 -0
  30. package/cli/commands/init.js +146 -0
  31. package/cli/commands/keys-generate.js +58 -0
  32. package/cli/commands/monitor.js +89 -0
  33. package/cli/commands/remote-shared.js +264 -0
  34. package/cli/commands/remote.js +634 -0
  35. package/cli/commands/server-start.js +96 -0
  36. package/cli/index.js +625 -0
  37. package/cli/package.json +21 -0
  38. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  39. package/dist/esm/app-review/app-review-manager.js +194 -0
  40. package/dist/esm/app-review/index.d.ts +5 -0
  41. package/dist/esm/app-review/index.js +5 -0
  42. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  43. package/dist/esm/app-review/platform-review-handler.js +137 -0
  44. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  45. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  46. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  47. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  48. package/dist/esm/app-review/types.d.ts +41 -0
  49. package/dist/esm/app-review/types.js +1 -0
  50. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  51. package/dist/esm/app-update/app-update-checker.js +227 -0
  52. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  53. package/dist/esm/app-update/app-update-installer.js +134 -0
  54. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  55. package/dist/esm/app-update/app-update-manager.js +198 -0
  56. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  57. package/dist/esm/app-update/app-update-notifier.js +99 -0
  58. package/dist/esm/app-update/index.d.ts +6 -0
  59. package/dist/esm/app-update/index.js +6 -0
  60. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  61. package/dist/esm/app-update/platform-app-update.js +138 -0
  62. package/dist/esm/app-update/types.d.ts +58 -0
  63. package/dist/esm/app-update/types.js +11 -0
  64. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  65. package/dist/esm/background-update/background-scheduler.js +332 -0
  66. package/dist/esm/background-update/index.d.ts +3 -0
  67. package/dist/esm/background-update/index.js +2 -0
  68. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  69. package/dist/esm/background-update/notification-manager.js +88 -0
  70. package/dist/esm/config/support.d.ts +9 -0
  71. package/dist/esm/config/support.js +9 -0
  72. package/dist/esm/core/analytics.d.ts +83 -0
  73. package/dist/esm/core/analytics.js +151 -0
  74. package/dist/esm/core/cache-manager.d.ts +72 -0
  75. package/dist/esm/core/cache-manager.js +274 -0
  76. package/dist/esm/core/config.d.ts +69 -0
  77. package/dist/esm/core/config.js +107 -0
  78. package/dist/esm/core/errors.d.ts +56 -0
  79. package/dist/esm/core/errors.js +85 -0
  80. package/dist/esm/core/event-emitter.d.ts +30 -0
  81. package/dist/esm/core/event-emitter.js +80 -0
  82. package/dist/esm/core/logger.d.ts +21 -0
  83. package/dist/esm/core/logger.js +108 -0
  84. package/dist/esm/core/performance.d.ts +53 -0
  85. package/dist/esm/core/performance.js +153 -0
  86. package/dist/esm/core/plugin-manager.d.ts +88 -0
  87. package/dist/esm/core/plugin-manager.js +224 -0
  88. package/dist/esm/core/security.d.ts +123 -0
  89. package/dist/esm/core/security.js +361 -0
  90. package/dist/esm/core/update-check.d.ts +121 -0
  91. package/dist/esm/core/update-check.js +127 -0
  92. package/dist/esm/definitions.d.ts +872 -0
  93. package/dist/esm/definitions.js +104 -0
  94. package/dist/esm/index.d.ts +14 -0
  95. package/dist/esm/index.js +18 -0
  96. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  97. package/dist/esm/live-update/bundle-manager.js +344 -0
  98. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  99. package/dist/esm/live-update/certificate-pinning.js +77 -0
  100. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  101. package/dist/esm/live-update/delta-processor.js +257 -0
  102. package/dist/esm/live-update/download-manager.d.ts +106 -0
  103. package/dist/esm/live-update/download-manager.js +412 -0
  104. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  105. package/dist/esm/live-update/rollout-checker.js +304 -0
  106. package/dist/esm/live-update/update-manager.d.ts +63 -0
  107. package/dist/esm/live-update/update-manager.js +321 -0
  108. package/dist/esm/live-update/version-manager.d.ts +93 -0
  109. package/dist/esm/live-update/version-manager.js +390 -0
  110. package/dist/esm/plugin.d.ts +3 -0
  111. package/dist/esm/plugin.js +848 -0
  112. package/dist/esm/security/crypto.d.ts +88 -0
  113. package/dist/esm/security/crypto.js +228 -0
  114. package/dist/esm/security/validator.d.ts +60 -0
  115. package/dist/esm/security/validator.js +142 -0
  116. package/dist/esm/types/app-identity.d.ts +36 -0
  117. package/dist/esm/types/app-identity.js +1 -0
  118. package/dist/esm/types/rollout.d.ts +91 -0
  119. package/dist/esm/types/rollout.js +25 -0
  120. package/dist/esm/web.d.ts +130 -0
  121. package/dist/esm/web.js +981 -0
  122. package/dist/plugin.cjs +1 -0
  123. package/dist/plugin.esm.js +1 -0
  124. package/dist/plugin.js +2 -0
  125. package/docs/CHANGELOG.md +1016 -0
  126. package/docs/KNOWN_LIMITATIONS.md +240 -0
  127. package/docs/MIGRATION.md +391 -0
  128. package/docs/protocol/CLIENT-PROTOCOL.md +199 -0
  129. package/docs/server-requirements.md +211 -0
  130. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  131. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  133. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  134. package/ios/Plugin/Info.plist +43 -0
  135. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  136. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  137. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  138. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  139. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  140. package/package.json +133 -4
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Rollout Checker
3
+ *
4
+ * Client-side rollout eligibility checking for staged deployments.
5
+ * Uses deterministic hashing for consistent rollout decisions.
6
+ */
7
+ import { toEpochMs } from '../types/rollout';
8
+ import { Logger } from '../core/logger';
9
+ import { ConfigManager } from '../core/config';
10
+ /**
11
+ * Rollout checker for determining update eligibility
12
+ */
13
+ export class RolloutChecker {
14
+ constructor() {
15
+ this.deviceInfoCache = null;
16
+ this.logger = Logger.getInstance();
17
+ this.configManager = ConfigManager.getInstance();
18
+ }
19
+ /**
20
+ * Check if device is eligible for update based on rollout config
21
+ */
22
+ async checkEligibility(rollout, deviceInfo) {
23
+ var _a;
24
+ // If rollouts are disabled in config, always eligible
25
+ if (!this.configManager.get('enableStagedRollouts')) {
26
+ return { eligible: true, reason: 'Staged rollouts disabled in config' };
27
+ }
28
+ // If rollout is not enabled, all devices are eligible
29
+ if (!rollout.enabled) {
30
+ return { eligible: true, reason: 'Rollout not enabled, all devices eligible' };
31
+ }
32
+ // Check time window
33
+ const timeCheck = this.checkTimeWindow(rollout);
34
+ if (!timeCheck.eligible) {
35
+ return timeCheck;
36
+ }
37
+ // Check scheduled rollout
38
+ if (((_a = rollout.schedule) === null || _a === void 0 ? void 0 : _a.type) === 'scheduled' && rollout.schedule.scheduledTime) {
39
+ const scheduledCheck = this.checkScheduled(rollout.schedule.scheduledTime);
40
+ if (!scheduledCheck.eligible) {
41
+ return scheduledCheck;
42
+ }
43
+ }
44
+ // Check target segments
45
+ if (rollout.targetSegments) {
46
+ const segmentCheck = this.checkSegments(rollout.targetSegments, deviceInfo);
47
+ if (!segmentCheck.eligible) {
48
+ return segmentCheck;
49
+ }
50
+ }
51
+ // Calculate current rollout percentage
52
+ const currentPercentage = this.calculateCurrentPercentage(rollout);
53
+ // Get device percentile
54
+ const devicePercentile = await this.getDevicePercentile(deviceInfo.deviceId);
55
+ // Check if device is in rollout percentage
56
+ if (devicePercentile > currentPercentage) {
57
+ return {
58
+ eligible: false,
59
+ reason: `Device percentile ${devicePercentile.toFixed(1)}% exceeds rollout ${currentPercentage}%`,
60
+ devicePercentile,
61
+ currentPercentage,
62
+ };
63
+ }
64
+ this.logger.debug('Device eligible for update', {
65
+ devicePercentile,
66
+ currentPercentage,
67
+ });
68
+ return {
69
+ eligible: true,
70
+ reason: 'Device eligible for update',
71
+ devicePercentile,
72
+ currentPercentage,
73
+ };
74
+ }
75
+ /**
76
+ * Check time window for rollout
77
+ */
78
+ checkTimeWindow(rollout) {
79
+ const now = Date.now();
80
+ const startTime = toEpochMs(rollout.startTime);
81
+ if (now < startTime) {
82
+ return {
83
+ eligible: false,
84
+ reason: `Rollout not started yet. Starts at ${new Date(startTime).toISOString()}`,
85
+ };
86
+ }
87
+ if (rollout.endTime) {
88
+ const endTime = toEpochMs(rollout.endTime);
89
+ if (now > endTime) {
90
+ return {
91
+ eligible: false,
92
+ reason: `Rollout ended at ${new Date(endTime).toISOString()}`,
93
+ };
94
+ }
95
+ }
96
+ return { eligible: true, reason: 'Within time window' };
97
+ }
98
+ /**
99
+ * Check scheduled start time
100
+ */
101
+ checkScheduled(scheduledTime) {
102
+ const now = Date.now();
103
+ const scheduled = toEpochMs(scheduledTime);
104
+ if (now < scheduled) {
105
+ return {
106
+ eligible: false,
107
+ reason: `Scheduled for ${new Date(scheduled).toISOString()}`,
108
+ };
109
+ }
110
+ return { eligible: true, reason: 'Scheduled time passed' };
111
+ }
112
+ /**
113
+ * Check target segments
114
+ */
115
+ checkSegments(segments, deviceInfo) {
116
+ // Platform check
117
+ if (segments.platforms && segments.platforms.length > 0) {
118
+ if (!segments.platforms.includes(deviceInfo.platform)) {
119
+ return {
120
+ eligible: false,
121
+ reason: `Platform ${deviceInfo.platform} not in target list: ${segments.platforms.join(', ')}`,
122
+ };
123
+ }
124
+ }
125
+ // App version checks
126
+ if (segments.minAppVersion) {
127
+ if (this.compareVersions(deviceInfo.appVersion, segments.minAppVersion) < 0) {
128
+ return {
129
+ eligible: false,
130
+ reason: `App version ${deviceInfo.appVersion} below minimum ${segments.minAppVersion}`,
131
+ };
132
+ }
133
+ }
134
+ if (segments.maxAppVersion) {
135
+ if (this.compareVersions(deviceInfo.appVersion, segments.maxAppVersion) > 0) {
136
+ return {
137
+ eligible: false,
138
+ reason: `App version ${deviceInfo.appVersion} above maximum ${segments.maxAppVersion}`,
139
+ };
140
+ }
141
+ }
142
+ // Device ID whitelist
143
+ if (segments.deviceIds && segments.deviceIds.length > 0) {
144
+ if (!segments.deviceIds.includes(deviceInfo.deviceId)) {
145
+ return {
146
+ eligible: false,
147
+ reason: 'Device not in whitelist',
148
+ };
149
+ }
150
+ }
151
+ // Region check
152
+ if (segments.regions && segments.regions.length > 0) {
153
+ if (!deviceInfo.region || !segments.regions.includes(deviceInfo.region)) {
154
+ return {
155
+ eligible: false,
156
+ reason: `Region ${deviceInfo.region || 'unknown'} not in target list: ${segments.regions.join(', ')}`,
157
+ };
158
+ }
159
+ }
160
+ return { eligible: true, reason: 'Segment checks passed' };
161
+ }
162
+ /**
163
+ * Calculate current rollout percentage based on schedule
164
+ */
165
+ calculateCurrentPercentage(rollout) {
166
+ if (!rollout.schedule || rollout.schedule.type !== 'gradual') {
167
+ return rollout.percentage;
168
+ }
169
+ const { gradualSteps, gradualInterval } = rollout.schedule;
170
+ if (!gradualSteps || !gradualInterval) {
171
+ return rollout.percentage;
172
+ }
173
+ const startTime = toEpochMs(rollout.startTime);
174
+ const elapsedHours = (Date.now() - startTime) / (1000 * 60 * 60);
175
+ const stepIndex = Math.floor(elapsedHours / gradualInterval);
176
+ if (stepIndex >= gradualSteps.length) {
177
+ return gradualSteps[gradualSteps.length - 1];
178
+ }
179
+ return gradualSteps[stepIndex];
180
+ }
181
+ /**
182
+ * Get deterministic percentile for device ID
183
+ * Uses SHA-256 hash for uniform distribution
184
+ */
185
+ async getDevicePercentile(deviceId) {
186
+ const hash = await this.hashString(deviceId);
187
+ return this.hashToPercentile(hash);
188
+ }
189
+ /**
190
+ * Hash a string using SHA-256
191
+ */
192
+ async hashString(input) {
193
+ const encoder = new TextEncoder();
194
+ const data = encoder.encode(input);
195
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
196
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
197
+ return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
198
+ }
199
+ /**
200
+ * Convert hash to percentile (0-100)
201
+ */
202
+ hashToPercentile(hash) {
203
+ const hashInt = parseInt(hash.substring(0, 8), 16);
204
+ const maxInt = parseInt('ffffffff', 16);
205
+ return (hashInt / maxInt) * 100;
206
+ }
207
+ /**
208
+ * Compare semantic versions
209
+ */
210
+ compareVersions(v1, v2) {
211
+ const cleanV1 = v1.split('-')[0];
212
+ const cleanV2 = v2.split('-')[0];
213
+ const parts1 = cleanV1.split('.').map(Number);
214
+ const parts2 = cleanV2.split('.').map(Number);
215
+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
216
+ const p1 = parts1[i] || 0;
217
+ const p2 = parts2[i] || 0;
218
+ if (p1 > p2)
219
+ return 1;
220
+ if (p1 < p2)
221
+ return -1;
222
+ }
223
+ return 0;
224
+ }
225
+ /**
226
+ * Set cached device info
227
+ */
228
+ setDeviceInfo(deviceInfo) {
229
+ this.deviceInfoCache = deviceInfo;
230
+ }
231
+ /**
232
+ * Get cached device info
233
+ */
234
+ getDeviceInfo() {
235
+ return this.deviceInfoCache;
236
+ }
237
+ /**
238
+ * Check if staged rollouts are enabled
239
+ */
240
+ isEnabled() {
241
+ return this.configManager.get('enableStagedRollouts');
242
+ }
243
+ }
244
+ /**
245
+ * Create rollout checker instance
246
+ */
247
+ export function createRolloutChecker() {
248
+ return new RolloutChecker();
249
+ }
250
+ /**
251
+ * Collect device information for rollout eligibility
252
+ */
253
+ export async function collectDeviceInfo() {
254
+ // Try to get Capacitor device info if available
255
+ let platform = 'web';
256
+ let osVersion = '';
257
+ try {
258
+ const { Device } = await import('@capacitor/device');
259
+ const info = await Device.getInfo();
260
+ platform = info.platform;
261
+ osVersion = info.osVersion;
262
+ }
263
+ catch (_a) {
264
+ // Running in web or Device plugin not available
265
+ platform = 'web';
266
+ osVersion = navigator.userAgent;
267
+ }
268
+ // Get or generate device ID
269
+ let deviceId = '';
270
+ try {
271
+ const { Preferences } = await import('@capacitor/preferences');
272
+ const { value } = await Preferences.get({ key: 'native_update_device_id' });
273
+ if (value) {
274
+ deviceId = value;
275
+ }
276
+ else {
277
+ deviceId = crypto.randomUUID();
278
+ await Preferences.set({ key: 'native_update_device_id', value: deviceId });
279
+ }
280
+ }
281
+ catch (_b) {
282
+ // Generate a session-based ID
283
+ deviceId = `web_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
284
+ }
285
+ // Get app version
286
+ let appVersion = '1.0.0';
287
+ try {
288
+ const { App } = await import('@capacitor/app');
289
+ const info = await App.getInfo();
290
+ appVersion = info.version;
291
+ }
292
+ catch (_c) {
293
+ // Use default version
294
+ }
295
+ return {
296
+ deviceId,
297
+ platform,
298
+ appVersion,
299
+ bundleVersion: '1.0.0', // Will be updated by the plugin
300
+ osVersion,
301
+ locale: navigator.language,
302
+ region: undefined, // Could be determined via geolocation or timezone
303
+ };
304
+ }
@@ -0,0 +1,63 @@
1
+ import type { UpdateOptions } from '../definitions';
2
+ /**
3
+ * Manages atomic bundle installation with rollback capability
4
+ */
5
+ export declare class UpdateManager {
6
+ private readonly pluginManager;
7
+ private readonly securityValidator;
8
+ private filesystem;
9
+ private updateInProgress;
10
+ private currentState;
11
+ constructor();
12
+ /**
13
+ * Initialize update manager
14
+ */
15
+ initialize(): Promise<void>;
16
+ /**
17
+ * Apply bundle update atomically
18
+ */
19
+ applyUpdate(bundleId: string, options?: UpdateOptions): Promise<void>;
20
+ /**
21
+ * Validate update before applying.
22
+ *
23
+ * Version-safety checks here are the last line of defense before a bundle
24
+ * is activated. We enforce two invariants:
25
+ * 1. Active-bundle monotonicity — new bundle must be strictly newer than
26
+ * whatever is currently active on this device.
27
+ * 2. Persisted high-water-mark — new bundle must be strictly newer than
28
+ * the highest version this device has ever applied in this channel.
29
+ * Catches an attacker who wipes the download cache (or serves an
30
+ * older manifest) to force a downgrade to a vulnerable build.
31
+ * The old `allowDowngrade` escape hatch was removed in v2 — downgrades are
32
+ * a debug/recovery flow and belong in a dedicated API, not an option flag.
33
+ */
34
+ private validateUpdate;
35
+ /**
36
+ * Create backup of current bundle
37
+ */
38
+ private createBackup;
39
+ /**
40
+ * Perform the actual update
41
+ */
42
+ private performUpdate;
43
+ /**
44
+ * Verify update was successful
45
+ */
46
+ private verifyUpdate;
47
+ /**
48
+ * Rollback to previous state
49
+ */
50
+ rollback(): Promise<void>;
51
+ /**
52
+ * Get current update progress
53
+ */
54
+ getUpdateProgress(): {
55
+ inProgress: boolean;
56
+ bundleId?: string;
57
+ startTime?: number;
58
+ };
59
+ /**
60
+ * Cancel current update (if possible)
61
+ */
62
+ cancelUpdate(): Promise<void>;
63
+ }
@@ -0,0 +1,321 @@
1
+ import { PluginManager } from '../core/plugin-manager';
2
+ import { UpdateError, ValidationError, ErrorCode } from '../core/errors';
3
+ import { SecurityValidator } from '../core/security';
4
+ import { Directory } from '@capacitor/filesystem';
5
+ /**
6
+ * Manages atomic bundle installation with rollback capability
7
+ */
8
+ export class UpdateManager {
9
+ constructor() {
10
+ this.filesystem = null;
11
+ this.updateInProgress = false;
12
+ this.currentState = null;
13
+ this.pluginManager = PluginManager.getInstance();
14
+ this.securityValidator = SecurityValidator.getInstance();
15
+ }
16
+ /**
17
+ * Initialize update manager
18
+ */
19
+ async initialize() {
20
+ this.filesystem = this.pluginManager.getConfigManager().get('filesystem');
21
+ if (!this.filesystem) {
22
+ throw new UpdateError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured');
23
+ }
24
+ }
25
+ /**
26
+ * Apply bundle update atomically
27
+ */
28
+ async applyUpdate(bundleId, options) {
29
+ var _a;
30
+ if (this.updateInProgress) {
31
+ throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Another update is already in progress');
32
+ }
33
+ const logger = this.pluginManager.getLogger();
34
+ const bundleManager = this.pluginManager.getBundleManager();
35
+ try {
36
+ this.updateInProgress = true;
37
+ logger.info('Starting bundle update', { bundleId });
38
+ // Get the new bundle
39
+ const newBundle = await bundleManager.getBundle(bundleId);
40
+ if (!newBundle) {
41
+ throw new UpdateError(ErrorCode.FILE_NOT_FOUND, `Bundle ${bundleId} not found`);
42
+ }
43
+ // Verify bundle is ready
44
+ if (newBundle.status !== 'READY' && newBundle.status !== 'ACTIVE') {
45
+ throw new UpdateError(ErrorCode.BUNDLE_NOT_READY, `Bundle ${bundleId} is not ready for installation`);
46
+ }
47
+ // Get current active bundle
48
+ const currentBundle = await bundleManager.getActiveBundle();
49
+ // Initialize update state
50
+ this.currentState = {
51
+ currentBundle,
52
+ newBundle,
53
+ backupPath: null,
54
+ startTime: Date.now(),
55
+ };
56
+ // Validate update
57
+ await this.validateUpdate(currentBundle, newBundle, options);
58
+ // Create backup of current state
59
+ if (currentBundle && currentBundle.bundleId !== 'default') {
60
+ this.currentState.backupPath = await this.createBackup(currentBundle);
61
+ }
62
+ // Apply the update
63
+ await this.performUpdate(newBundle);
64
+ // Verify the update
65
+ await this.verifyUpdate(newBundle);
66
+ // Mark as active
67
+ await bundleManager.setActiveBundle(bundleId);
68
+ // Advance the monotonic high-water mark so future update checks and
69
+ // reinstalls cannot be tricked into applying an older version.
70
+ const versionManager = this.pluginManager.getVersionManager();
71
+ const configManager = this.pluginManager.getConfigManager();
72
+ await versionManager.rememberAppliedVersion(configManager.get('channel'), newBundle.version);
73
+ // Auto-cleanup by default. The old opt-in flag left most
74
+ // integrations accumulating bundles forever, which is a disk
75
+ // exhaustion path on devices with limited storage. Host apps
76
+ // that genuinely want every historical bundle can pass
77
+ // cleanupOldBundles: false explicitly.
78
+ const shouldCleanup = (options === null || options === void 0 ? void 0 : options.cleanupOldBundles) !== false;
79
+ if (shouldCleanup) {
80
+ const keep = (_a = options === null || options === void 0 ? void 0 : options.keepBundleCount) !== null && _a !== void 0 ? _a : 3;
81
+ await bundleManager.cleanupOldBundles(keep);
82
+ }
83
+ logger.info('Bundle update completed successfully', {
84
+ bundleId,
85
+ version: newBundle.version,
86
+ duration: Date.now() - this.currentState.startTime,
87
+ });
88
+ // Clear state
89
+ this.currentState = null;
90
+ }
91
+ catch (error) {
92
+ logger.error('Bundle update failed', error);
93
+ // Attempt rollback
94
+ if (this.currentState) {
95
+ await this.rollback();
96
+ }
97
+ throw error;
98
+ }
99
+ finally {
100
+ this.updateInProgress = false;
101
+ }
102
+ }
103
+ /**
104
+ * Validate update before applying.
105
+ *
106
+ * Version-safety checks here are the last line of defense before a bundle
107
+ * is activated. We enforce two invariants:
108
+ * 1. Active-bundle monotonicity — new bundle must be strictly newer than
109
+ * whatever is currently active on this device.
110
+ * 2. Persisted high-water-mark — new bundle must be strictly newer than
111
+ * the highest version this device has ever applied in this channel.
112
+ * Catches an attacker who wipes the download cache (or serves an
113
+ * older manifest) to force a downgrade to a vulnerable build.
114
+ * The old `allowDowngrade` escape hatch was removed in v2 — downgrades are
115
+ * a debug/recovery flow and belong in a dedicated API, not an option flag.
116
+ */
117
+ async validateUpdate(currentBundle, newBundle, _options) {
118
+ const logger = this.pluginManager.getLogger();
119
+ const versionManager = this.pluginManager.getVersionManager();
120
+ const configManager = this.pluginManager.getConfigManager();
121
+ if (currentBundle &&
122
+ versionManager.shouldBlockDowngrade(currentBundle.version, newBundle.version)) {
123
+ throw new ValidationError(ErrorCode.VERSION_DOWNGRADE, `Cannot downgrade from ${currentBundle.version} to ${newBundle.version}`);
124
+ }
125
+ const channel = configManager.get('channel');
126
+ const maxSeen = await versionManager.getMaxSeenVersion(channel);
127
+ if (maxSeen &&
128
+ versionManager.shouldBlockDowngrade(maxSeen, newBundle.version)) {
129
+ throw new ValidationError(ErrorCode.VERSION_DOWNGRADE, `Cannot apply ${newBundle.version} - device has previously applied ${maxSeen} on channel ${channel}`);
130
+ }
131
+ // Verify bundle integrity
132
+ if (!newBundle.verified) {
133
+ logger.warn('Bundle not verified, verifying now', {
134
+ bundleId: newBundle.bundleId,
135
+ });
136
+ // Load bundle data
137
+ const downloadManager = this.pluginManager.getDownloadManager();
138
+ const blob = await downloadManager.loadBlob(newBundle.bundleId);
139
+ if (!blob) {
140
+ throw new UpdateError(ErrorCode.FILE_NOT_FOUND, 'Bundle data not found');
141
+ }
142
+ // Verify checksum
143
+ const arrayBuffer = await blob.arrayBuffer();
144
+ const isValid = await this.securityValidator.verifyChecksum(arrayBuffer, newBundle.checksum);
145
+ if (!isValid) {
146
+ throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Bundle checksum verification failed');
147
+ }
148
+ // Verify signature if enabled
149
+ if (newBundle.signature) {
150
+ const signatureValid = await this.securityValidator.verifySignature(arrayBuffer, newBundle.signature);
151
+ if (!signatureValid) {
152
+ throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Bundle signature verification failed');
153
+ }
154
+ }
155
+ // Mark as verified
156
+ await this.pluginManager
157
+ .getBundleManager()
158
+ .markBundleAsVerified(newBundle.bundleId);
159
+ }
160
+ logger.debug('Bundle validation passed', { bundleId: newBundle.bundleId });
161
+ }
162
+ /**
163
+ * Create backup of current bundle
164
+ */
165
+ async createBackup(bundle) {
166
+ const backupPath = `backups/${bundle.bundleId}_${Date.now()}`;
167
+ const logger = this.pluginManager.getLogger();
168
+ try {
169
+ // Create backup directory
170
+ await this.filesystem.mkdir({
171
+ path: backupPath,
172
+ directory: Directory.Data,
173
+ recursive: true,
174
+ });
175
+ // Copy bundle files
176
+ await this.filesystem.copy({
177
+ from: bundle.path,
178
+ to: backupPath,
179
+ directory: Directory.Data,
180
+ });
181
+ logger.info('Backup created', { bundleId: bundle.bundleId, backupPath });
182
+ return backupPath;
183
+ }
184
+ catch (error) {
185
+ logger.error('Failed to create backup', error);
186
+ throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to create backup', undefined, error);
187
+ }
188
+ }
189
+ /**
190
+ * Perform the actual update
191
+ */
192
+ async performUpdate(bundle) {
193
+ const logger = this.pluginManager.getLogger();
194
+ try {
195
+ // Extract bundle to target location
196
+ const targetPath = `active/${bundle.bundleId}`;
197
+ // Create target directory
198
+ await this.filesystem.mkdir({
199
+ path: targetPath,
200
+ directory: Directory.Data,
201
+ recursive: true,
202
+ });
203
+ // Copy bundle files
204
+ await this.filesystem.copy({
205
+ from: bundle.path,
206
+ to: targetPath,
207
+ directory: Directory.Data,
208
+ });
209
+ // Update bundle path
210
+ bundle.path = targetPath;
211
+ logger.debug('Bundle files installed', {
212
+ bundleId: bundle.bundleId,
213
+ targetPath,
214
+ });
215
+ }
216
+ catch (error) {
217
+ throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Failed to install bundle files', undefined, error);
218
+ }
219
+ }
220
+ /**
221
+ * Verify update was successful
222
+ */
223
+ async verifyUpdate(bundle) {
224
+ try {
225
+ // Check if main bundle files exist
226
+ const indexPath = `${bundle.path}/index.html`;
227
+ await this.filesystem.stat({
228
+ path: indexPath,
229
+ directory: Directory.Data,
230
+ });
231
+ // Additional verification can be added here
232
+ }
233
+ catch (error) {
234
+ throw new UpdateError(ErrorCode.UPDATE_FAILED, 'Bundle verification failed after installation', undefined, error);
235
+ }
236
+ }
237
+ /**
238
+ * Rollback to previous state
239
+ */
240
+ async rollback() {
241
+ var _a;
242
+ if (!this.currentState) {
243
+ throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'No update state to rollback');
244
+ }
245
+ const logger = this.pluginManager.getLogger();
246
+ logger.warn('Starting rollback', {
247
+ from: this.currentState.newBundle.bundleId,
248
+ to: ((_a = this.currentState.currentBundle) === null || _a === void 0 ? void 0 : _a.bundleId) || 'default',
249
+ });
250
+ try {
251
+ const bundleManager = this.pluginManager.getBundleManager();
252
+ // Restore from backup if available
253
+ if (this.currentState.backupPath && this.currentState.currentBundle) {
254
+ const restoredPath = `active/${this.currentState.currentBundle.bundleId}`;
255
+ await this.filesystem.copy({
256
+ from: this.currentState.backupPath,
257
+ to: restoredPath,
258
+ directory: Directory.Data,
259
+ });
260
+ // Update bundle path
261
+ this.currentState.currentBundle.path = restoredPath;
262
+ await bundleManager.saveBundleInfo(this.currentState.currentBundle);
263
+ }
264
+ // Restore active bundle
265
+ if (this.currentState.currentBundle) {
266
+ await bundleManager.setActiveBundle(this.currentState.currentBundle.bundleId);
267
+ }
268
+ else {
269
+ // No previous bundle, clear active
270
+ await bundleManager.clearActiveBundle();
271
+ }
272
+ logger.info('Rollback completed successfully');
273
+ }
274
+ catch (error) {
275
+ logger.error('Rollback failed', error);
276
+ throw new UpdateError(ErrorCode.ROLLBACK_FAILED, 'Failed to rollback update', undefined, error);
277
+ }
278
+ finally {
279
+ // Clean up backup
280
+ if (this.currentState.backupPath) {
281
+ try {
282
+ await this.filesystem.rmdir({
283
+ path: this.currentState.backupPath,
284
+ directory: Directory.Data,
285
+ recursive: true,
286
+ });
287
+ }
288
+ catch (error) {
289
+ logger.warn('Failed to clean up backup', error);
290
+ }
291
+ }
292
+ }
293
+ }
294
+ /**
295
+ * Get current update progress
296
+ */
297
+ getUpdateProgress() {
298
+ var _a, _b;
299
+ return {
300
+ inProgress: this.updateInProgress,
301
+ bundleId: (_a = this.currentState) === null || _a === void 0 ? void 0 : _a.newBundle.bundleId,
302
+ startTime: (_b = this.currentState) === null || _b === void 0 ? void 0 : _b.startTime,
303
+ };
304
+ }
305
+ /**
306
+ * Cancel current update (if possible)
307
+ */
308
+ async cancelUpdate() {
309
+ if (!this.updateInProgress || !this.currentState) {
310
+ return;
311
+ }
312
+ const logger = this.pluginManager.getLogger();
313
+ logger.warn('Cancelling update', {
314
+ bundleId: this.currentState.newBundle.bundleId,
315
+ });
316
+ // Attempt rollback
317
+ await this.rollback();
318
+ this.updateInProgress = false;
319
+ this.currentState = null;
320
+ }
321
+ }