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,981 @@
1
+ import { WebPlugin } from '@capacitor/core';
2
+ import { SyncStatus, BundleStatus, UpdateErrorCode } from './definitions';
3
+ import { ConfigManager } from './core/config';
4
+ import { Logger } from './core/logger';
5
+ // Module-level logger so we never leak sensitive headers / tokens
6
+ // through raw console.* calls. The Logger sanitises payloads (paths,
7
+ // keys, secrets) and respects the runtime log-level switch.
8
+ const logger = new Logger('NativeUpdateWeb');
9
+ export class NativeUpdateWeb extends WebPlugin {
10
+ constructor() {
11
+ super();
12
+ this.config = {};
13
+ this.currentBundle = null;
14
+ this.bundles = new Map();
15
+ this.lastReviewRequest = 0;
16
+ this.launchCount = 0;
17
+ this.backgroundUpdateStatus = {
18
+ enabled: false,
19
+ isRunning: false,
20
+ checkCount: 0,
21
+ failureCount: 0,
22
+ };
23
+ this.backgroundCheckInterval = null;
24
+ this.isConfigured = false;
25
+ // Single-slot cache of the most recently downloaded bundle's bytes so a
26
+ // follow-up validateUpdate() on the same URL doesn't re-download the
27
+ // whole bundle just to hash it. Overwritten on each download().
28
+ this.downloadedBundleBytes = null;
29
+ this.configManager = ConfigManager.getInstance();
30
+ this.loadStoredData();
31
+ this.incrementLaunchCount();
32
+ }
33
+ /**
34
+ * Configuration and Core Methods
35
+ */
36
+ async configure(options) {
37
+ // Validate and store the plugin config using ConfigManager
38
+ // This will throw if baseUrl is not HTTPS
39
+ if (options.config) {
40
+ this.configManager.configure(options.config);
41
+ this.isConfigured = true;
42
+ this.saveConfiguration();
43
+ }
44
+ }
45
+ async getSecurityInfo() {
46
+ var _a, _b, _c, _d, _e, _f, _g;
47
+ return {
48
+ enforceHttps: ((_a = this.config.security) === null || _a === void 0 ? void 0 : _a.enforceHttps) !== false,
49
+ certificatePinning: {
50
+ enabled: ((_c = (_b = this.config.security) === null || _b === void 0 ? void 0 : _b.certificatePinning) === null || _c === void 0 ? void 0 : _c.enabled) || false,
51
+ pins: ((_e = (_d = this.config.security) === null || _d === void 0 ? void 0 : _d.certificatePinning) === null || _e === void 0 ? void 0 : _e.pins) || [],
52
+ },
53
+ validateInputs: ((_f = this.config.security) === null || _f === void 0 ? void 0 : _f.validateInputs) !== false,
54
+ secureStorage: ((_g = this.config.security) === null || _g === void 0 ? void 0 : _g.secureStorage) !== false,
55
+ };
56
+ }
57
+ /**
58
+ * Live Update Methods
59
+ */
60
+ async sync(_options) {
61
+ var _a;
62
+ // Require configuration before sync
63
+ if (!this.isConfigured) {
64
+ throw this.createError(UpdateErrorCode.NOT_CONFIGURED, 'Plugin not configured. Call configure() first.');
65
+ }
66
+ try {
67
+ // In web, we can check for service worker updates
68
+ if ('serviceWorker' in navigator) {
69
+ const registration = await navigator.serviceWorker.getRegistration();
70
+ if (registration) {
71
+ await registration.update();
72
+ if (registration.waiting) {
73
+ // There's an update waiting
74
+ registration.waiting.postMessage({ type: 'SKIP_WAITING' });
75
+ return {
76
+ status: SyncStatus.UPDATE_AVAILABLE,
77
+ version: 'web-update',
78
+ description: 'Service worker update available',
79
+ };
80
+ }
81
+ }
82
+ }
83
+ return {
84
+ status: SyncStatus.UP_TO_DATE,
85
+ version: ((_a = this.currentBundle) === null || _a === void 0 ? void 0 : _a.version) || '1.0.0',
86
+ };
87
+ }
88
+ catch (error) {
89
+ return {
90
+ status: SyncStatus.ERROR,
91
+ error: this.createError(UpdateErrorCode.UNKNOWN_ERROR, error.message),
92
+ };
93
+ }
94
+ }
95
+ async download(options) {
96
+ var _a, _b;
97
+ if (!options.url.startsWith('https://') &&
98
+ ((_a = this.config.security) === null || _a === void 0 ? void 0 : _a.enforceHttps) !== false) {
99
+ throw this.createError(UpdateErrorCode.INSECURE_URL, 'Download URL must use HTTPS');
100
+ }
101
+ const bundleId = `bundle-${Date.now()}`;
102
+ const bundle = {
103
+ bundleId,
104
+ version: options.version,
105
+ path: options.url,
106
+ downloadTime: Date.now(),
107
+ size: 0,
108
+ status: BundleStatus.DOWNLOADING,
109
+ checksum: options.checksum,
110
+ signature: options.signature,
111
+ verified: false,
112
+ };
113
+ this.bundles.set(bundleId, bundle);
114
+ // Actually fetch the bundle so we hash REAL bytes, not the bundleId
115
+ // string. This was a P0: validateChecksum used to receive `bundleId`
116
+ // and silently fail (or pass) regardless of the bundle contents.
117
+ let bundleBytes;
118
+ try {
119
+ const response = await fetch(options.url);
120
+ if (!response.ok) {
121
+ throw new Error(`HTTP ${response.status}`);
122
+ }
123
+ const reader = (_b = response.body) === null || _b === void 0 ? void 0 : _b.getReader();
124
+ const contentLength = Number(response.headers.get('content-length') || 0);
125
+ if (reader) {
126
+ const chunks = [];
127
+ let received = 0;
128
+ while (true) {
129
+ const { done, value } = await reader.read();
130
+ if (done)
131
+ break;
132
+ chunks.push(value);
133
+ received += value.length;
134
+ if (contentLength > 0) {
135
+ await this.notifyListeners('downloadProgress', {
136
+ percent: Math.round((received / contentLength) * 100),
137
+ bytesDownloaded: received,
138
+ totalBytes: contentLength,
139
+ bundleId,
140
+ });
141
+ }
142
+ }
143
+ const combined = new Uint8Array(received);
144
+ let offset = 0;
145
+ for (const chunk of chunks) {
146
+ combined.set(chunk, offset);
147
+ offset += chunk.length;
148
+ }
149
+ bundleBytes = combined.buffer;
150
+ }
151
+ else {
152
+ bundleBytes = await response.arrayBuffer();
153
+ }
154
+ }
155
+ catch (error) {
156
+ bundle.status = BundleStatus.FAILED;
157
+ this.bundles.delete(bundleId);
158
+ throw this.createError(UpdateErrorCode.NETWORK_ERROR, `Failed to download bundle: ${error.message}`);
159
+ }
160
+ bundle.size = bundleBytes.byteLength;
161
+ let verified = false;
162
+ if (options.checksum) {
163
+ const checksumValid = await this.validateChecksum(bundleBytes, options.checksum);
164
+ if (!checksumValid) {
165
+ bundle.status = BundleStatus.FAILED;
166
+ this.bundles.delete(bundleId);
167
+ throw this.createError(UpdateErrorCode.CHECKSUM_ERROR, 'Bundle checksum verification failed');
168
+ }
169
+ verified = true;
170
+ }
171
+ if (options.signature) {
172
+ const signatureValid = await this.validateSignature(bundleBytes, options.signature);
173
+ if (!signatureValid) {
174
+ bundle.status = BundleStatus.FAILED;
175
+ this.bundles.delete(bundleId);
176
+ throw this.createError(UpdateErrorCode.SIGNATURE_ERROR, 'Bundle signature verification failed');
177
+ }
178
+ verified = true;
179
+ }
180
+ bundle.status = BundleStatus.READY;
181
+ bundle.verified = verified;
182
+ this.downloadedBundleBytes = { path: options.url, bytes: bundleBytes };
183
+ this.saveStoredData();
184
+ await this.notifyListeners('updateStateChanged', {
185
+ status: bundle.status,
186
+ bundleId: bundle.bundleId,
187
+ version: bundle.version,
188
+ });
189
+ return bundle;
190
+ }
191
+ async set(bundle) {
192
+ if (!this.bundles.has(bundle.bundleId)) {
193
+ throw this.createError(UpdateErrorCode.UNKNOWN_ERROR, 'Bundle not found');
194
+ }
195
+ const stored = this.bundles.get(bundle.bundleId);
196
+ if (!stored.verified) {
197
+ throw this.createError(UpdateErrorCode.SIGNATURE_ERROR, `Refusing to activate unverified bundle ${bundle.bundleId}`);
198
+ }
199
+ const previousBundle = this.currentBundle;
200
+ this.currentBundle = stored;
201
+ this.currentBundle.status = BundleStatus.ACTIVE;
202
+ if (previousBundle) {
203
+ previousBundle.status = BundleStatus.READY;
204
+ }
205
+ this.saveStoredData();
206
+ }
207
+ async reload() {
208
+ // In web, we can reload the page
209
+ if (typeof window !== 'undefined') {
210
+ window.location.reload();
211
+ }
212
+ }
213
+ async reset() {
214
+ this.currentBundle = null;
215
+ this.bundles.clear();
216
+ this.saveStoredData();
217
+ // Clear service worker cache if available
218
+ if ('caches' in window) {
219
+ const cacheNames = await caches.keys();
220
+ await Promise.all(cacheNames.map((name) => caches.delete(name)));
221
+ }
222
+ }
223
+ async current() {
224
+ return this.currentBundle || this.createDefaultBundle();
225
+ }
226
+ async list() {
227
+ return Array.from(this.bundles.values());
228
+ }
229
+ async delete(options) {
230
+ if (options.bundleId) {
231
+ this.bundles.delete(options.bundleId);
232
+ }
233
+ else if (options.keepVersions !== undefined) {
234
+ const sortedBundles = Array.from(this.bundles.values()).sort((a, b) => b.downloadTime - a.downloadTime);
235
+ const bundlesToDelete = sortedBundles.slice(options.keepVersions);
236
+ bundlesToDelete.forEach((bundle) => this.bundles.delete(bundle.bundleId));
237
+ }
238
+ else if (options.olderThan !== undefined) {
239
+ const cutoffTime = options.olderThan;
240
+ Array.from(this.bundles.values())
241
+ .filter((bundle) => bundle.downloadTime < cutoffTime)
242
+ .forEach((bundle) => this.bundles.delete(bundle.bundleId));
243
+ }
244
+ this.saveStoredData();
245
+ }
246
+ async notifyAppReady() {
247
+ if (this.currentBundle) {
248
+ this.currentBundle.verified = true;
249
+ this.saveStoredData();
250
+ }
251
+ }
252
+ async getLatest() {
253
+ // In web, check for service worker updates
254
+ if ('serviceWorker' in navigator) {
255
+ const registration = await navigator.serviceWorker.getRegistration();
256
+ if (registration === null || registration === void 0 ? void 0 : registration.waiting) {
257
+ return {
258
+ available: true,
259
+ version: 'web-update',
260
+ notes: 'Service worker update available',
261
+ };
262
+ }
263
+ }
264
+ return {
265
+ available: false,
266
+ };
267
+ }
268
+ async getAppIdentity() {
269
+ // Web clients identify to the update backend via the browser-enforced
270
+ // Origin header, so no identity fields are needed here.
271
+ return { platform: 'web' };
272
+ }
273
+ async setChannel(channel) {
274
+ if (!this.config.liveUpdate) {
275
+ this.config.liveUpdate = {};
276
+ }
277
+ this.config.liveUpdate.channel = channel;
278
+ this.saveConfiguration();
279
+ }
280
+ /**
281
+ * @deprecated since v2. See NativeUpdatePluginWeb.setUpdateUrl in plugin.ts.
282
+ * Update URL is locked after initialize(); this method is a no-op.
283
+ */
284
+ async setUpdateUrl(url) {
285
+ void url;
286
+ logger.warn('setUpdateUrl() is deprecated and ignored. Update URL is locked after initialize().');
287
+ return;
288
+ }
289
+ async validateUpdate(options) {
290
+ var _a;
291
+ // bundlePath on web is the bundle URL (we don't persist bytes locally
292
+ // here). Reuse the bytes from the last download() when the URL matches;
293
+ // only re-fetch when validating a bundle we never downloaded.
294
+ let bundleBytes;
295
+ if (((_a = this.downloadedBundleBytes) === null || _a === void 0 ? void 0 : _a.path) === options.bundlePath) {
296
+ bundleBytes = this.downloadedBundleBytes.bytes;
297
+ }
298
+ else {
299
+ try {
300
+ const response = await fetch(options.bundlePath);
301
+ if (!response.ok) {
302
+ return {
303
+ isValid: false,
304
+ error: `Failed to fetch bundle for validation: HTTP ${response.status}`,
305
+ };
306
+ }
307
+ bundleBytes = await response.arrayBuffer();
308
+ }
309
+ catch (error) {
310
+ return {
311
+ isValid: false,
312
+ error: `Failed to fetch bundle for validation: ${error.message}`,
313
+ };
314
+ }
315
+ }
316
+ const checksumValid = await this.validateChecksum(bundleBytes, options.checksum);
317
+ const signatureValid = options.signature
318
+ ? await this.validateSignature(bundleBytes, options.signature)
319
+ : true;
320
+ const sizeValid = options.maxSize
321
+ ? bundleBytes.byteLength <= options.maxSize
322
+ : true;
323
+ const isValid = checksumValid && signatureValid && sizeValid;
324
+ return {
325
+ isValid,
326
+ error: isValid ? undefined : 'Validation failed',
327
+ details: {
328
+ checksumValid,
329
+ signatureValid,
330
+ sizeValid,
331
+ versionValid: true,
332
+ },
333
+ };
334
+ }
335
+ /**
336
+ * Convenience Methods
337
+ */
338
+ async checkForUpdate() {
339
+ var _a;
340
+ const currentVersion = ((_a = this.currentBundle) === null || _a === void 0 ? void 0 : _a.version) || '1.0.0';
341
+ // Check for service worker updates or server updates
342
+ const latest = await this.getLatest();
343
+ return {
344
+ available: latest.available,
345
+ currentVersion,
346
+ latestVersion: latest.version,
347
+ url: latest.url,
348
+ mandatory: latest.mandatory,
349
+ notes: latest.notes,
350
+ size: latest.size,
351
+ checksum: latest.checksum,
352
+ };
353
+ }
354
+ async downloadUpdate(options) {
355
+ // Check for update first if no options provided
356
+ let url = options === null || options === void 0 ? void 0 : options.url;
357
+ let version = options === null || options === void 0 ? void 0 : options.version;
358
+ let checksum = (options === null || options === void 0 ? void 0 : options.checksum) || '';
359
+ if (!url || !version) {
360
+ const updateInfo = await this.checkForUpdate();
361
+ if (!updateInfo.available || !updateInfo.url) {
362
+ throw this.createError(UpdateErrorCode.UPDATE_NOT_AVAILABLE, 'No update available to download');
363
+ }
364
+ url = url || updateInfo.url;
365
+ version = version || updateInfo.latestVersion || 'latest';
366
+ checksum = checksum || updateInfo.checksum || '';
367
+ }
368
+ // Download using the standard download method
369
+ return this.download({
370
+ url,
371
+ version,
372
+ checksum,
373
+ });
374
+ }
375
+ async applyUpdate(bundleId) {
376
+ // Find the bundle to apply
377
+ let bundle;
378
+ if (bundleId) {
379
+ bundle = this.bundles.get(bundleId);
380
+ }
381
+ else {
382
+ // Find the most recent ready bundle
383
+ const readyBundles = Array.from(this.bundles.values())
384
+ .filter(b => b.status === BundleStatus.READY)
385
+ .sort((a, b) => b.downloadTime - a.downloadTime);
386
+ bundle = readyBundles[0];
387
+ }
388
+ if (!bundle) {
389
+ throw this.createError(UpdateErrorCode.UNKNOWN_ERROR, 'No ready bundle found to apply');
390
+ }
391
+ // Set the bundle as active and reload
392
+ await this.set(bundle);
393
+ await this.reload();
394
+ }
395
+ async cancelDownload(bundleId) {
396
+ // In web implementation, we can't truly cancel an ongoing fetch
397
+ // But we can remove the bundle from tracking
398
+ const bundle = this.bundles.get(bundleId);
399
+ if (bundle && bundle.status === BundleStatus.DOWNLOADING) {
400
+ bundle.status = BundleStatus.FAILED;
401
+ this.bundles.delete(bundleId);
402
+ this.saveStoredData();
403
+ }
404
+ }
405
+ async cancelAllDownloads() {
406
+ const downloadingBundles = Array.from(this.bundles.values())
407
+ .filter(b => b.status === BundleStatus.DOWNLOADING);
408
+ for (const bundle of downloadingBundles) {
409
+ bundle.status = BundleStatus.FAILED;
410
+ this.bundles.delete(bundle.bundleId);
411
+ }
412
+ this.saveStoredData();
413
+ }
414
+ async isDownloading(bundleId) {
415
+ const bundle = this.bundles.get(bundleId);
416
+ return (bundle === null || bundle === void 0 ? void 0 : bundle.status) === BundleStatus.DOWNLOADING;
417
+ }
418
+ async getActiveDownloadCount() {
419
+ return Array.from(this.bundles.values())
420
+ .filter(b => b.status === BundleStatus.DOWNLOADING)
421
+ .length;
422
+ }
423
+ /**
424
+ * App Update Methods
425
+ */
426
+ async getAppUpdateInfo() {
427
+ return {
428
+ updateAvailable: false,
429
+ currentVersion: '1.0.0',
430
+ immediateUpdateAllowed: false,
431
+ flexibleUpdateAllowed: false,
432
+ };
433
+ }
434
+ async performImmediateUpdate() {
435
+ throw this.createError(UpdateErrorCode.PLATFORM_NOT_SUPPORTED, 'App updates are not supported on web platform');
436
+ }
437
+ async startFlexibleUpdate() {
438
+ throw this.createError(UpdateErrorCode.PLATFORM_NOT_SUPPORTED, 'App updates are not supported on web platform');
439
+ }
440
+ async completeFlexibleUpdate() {
441
+ throw this.createError(UpdateErrorCode.PLATFORM_NOT_SUPPORTED, 'App updates are not supported on web platform');
442
+ }
443
+ async openAppStore(_options) {
444
+ var _a, _b, _c, _d;
445
+ // Get configured store URL
446
+ const storeUrl = ((_b = (_a = this.config.appUpdate) === null || _a === void 0 ? void 0 : _a.storeUrl) === null || _b === void 0 ? void 0 : _b.android) ||
447
+ ((_d = (_c = this.config.appUpdate) === null || _c === void 0 ? void 0 : _c.storeUrl) === null || _d === void 0 ? void 0 : _d.ios) ||
448
+ this.getConfiguredReviewUrl();
449
+ if (!storeUrl) {
450
+ throw this.createError(UpdateErrorCode.INVALID_CONFIG, 'No app store URL configured. Set appUpdate.storeUrl.ios or appUpdate.storeUrl.android in plugin config.');
451
+ }
452
+ window.open(storeUrl, '_blank');
453
+ }
454
+ /**
455
+ * App Review Methods
456
+ */
457
+ async requestReview() {
458
+ var _a;
459
+ const canRequest = await this.canRequestReview();
460
+ if (!canRequest.canRequest) {
461
+ return {
462
+ displayed: false,
463
+ error: canRequest.reason,
464
+ };
465
+ }
466
+ // Update last request time
467
+ this.lastReviewRequest = Date.now();
468
+ (_a = this.getLocalStorage()) === null || _a === void 0 ? void 0 : _a.setItem('native-update-last-review', this.lastReviewRequest.toString());
469
+ // In web, we could show a custom modal or redirect to a review page
470
+ // Note: Web platform cannot display native in-app review dialogs
471
+ // We can offer a fallback redirect, but `displayed` reflects native capability
472
+ const reviewUrl = this.getConfiguredReviewUrl();
473
+ // Guard against environments where confirm is not available (e.g., test environments)
474
+ if (typeof confirm === 'function' && reviewUrl) {
475
+ const shouldRedirect = confirm('Would you like to leave a review for our app?');
476
+ if (shouldRedirect && typeof window !== 'undefined' && window.open) {
477
+ window.open(reviewUrl, '_blank');
478
+ }
479
+ }
480
+ // Web platform returns displayed: false because we cannot show native review dialog
481
+ return {
482
+ displayed: false,
483
+ };
484
+ }
485
+ async canRequestReview() {
486
+ const config = this.config.appReview;
487
+ const now = Date.now();
488
+ const installDate = this.getInstallDate();
489
+ const daysSinceInstall = (now - installDate) / (1000 * 60 * 60 * 24);
490
+ // Check minimum days since install
491
+ if ((config === null || config === void 0 ? void 0 : config.minimumDaysSinceInstall) &&
492
+ daysSinceInstall < config.minimumDaysSinceInstall) {
493
+ return {
494
+ canRequest: false,
495
+ reason: 'Not enough days since install',
496
+ };
497
+ }
498
+ // Check minimum days since last prompt
499
+ if ((config === null || config === void 0 ? void 0 : config.minimumDaysSinceLastPrompt) && this.lastReviewRequest > 0) {
500
+ const daysSinceLastPrompt = (now - this.lastReviewRequest) / (1000 * 60 * 60 * 24);
501
+ if (daysSinceLastPrompt < config.minimumDaysSinceLastPrompt) {
502
+ return {
503
+ canRequest: false,
504
+ reason: 'Too soon since last review request',
505
+ };
506
+ }
507
+ }
508
+ // Check minimum launch count
509
+ if ((config === null || config === void 0 ? void 0 : config.minimumLaunchCount) &&
510
+ this.launchCount < config.minimumLaunchCount) {
511
+ return {
512
+ canRequest: false,
513
+ reason: 'Not enough app launches',
514
+ };
515
+ }
516
+ return {
517
+ canRequest: true,
518
+ };
519
+ }
520
+ /**
521
+ * Background Update Methods
522
+ */
523
+ async enableBackgroundUpdates(config) {
524
+ if (!this.config.backgroundUpdate) {
525
+ this.config.backgroundUpdate = config;
526
+ }
527
+ else {
528
+ this.config.backgroundUpdate = Object.assign(Object.assign({}, this.config.backgroundUpdate), config);
529
+ }
530
+ this.backgroundUpdateStatus.enabled = config.enabled;
531
+ if (config.enabled) {
532
+ await this.scheduleBackgroundCheck(config.checkInterval);
533
+ }
534
+ else {
535
+ await this.disableBackgroundUpdates();
536
+ }
537
+ this.saveConfiguration();
538
+ }
539
+ async disableBackgroundUpdates() {
540
+ if (this.backgroundCheckInterval) {
541
+ clearInterval(this.backgroundCheckInterval);
542
+ this.backgroundCheckInterval = null;
543
+ }
544
+ this.backgroundUpdateStatus.enabled = false;
545
+ this.backgroundUpdateStatus.isRunning = false;
546
+ this.backgroundUpdateStatus.currentTaskId = undefined;
547
+ if (this.config.backgroundUpdate) {
548
+ this.config.backgroundUpdate.enabled = false;
549
+ }
550
+ this.saveConfiguration();
551
+ }
552
+ async getBackgroundUpdateStatus() {
553
+ return Object.assign({}, this.backgroundUpdateStatus);
554
+ }
555
+ async scheduleBackgroundCheck(interval) {
556
+ if (this.backgroundCheckInterval) {
557
+ clearInterval(this.backgroundCheckInterval);
558
+ }
559
+ this.backgroundCheckInterval = setInterval(async () => {
560
+ if (this.backgroundUpdateStatus.enabled &&
561
+ !this.backgroundUpdateStatus.isRunning) {
562
+ await this.triggerBackgroundCheck();
563
+ }
564
+ }, interval);
565
+ this.backgroundUpdateStatus.nextCheckTime = Date.now() + interval;
566
+ }
567
+ async triggerBackgroundCheck() {
568
+ if (!this.backgroundUpdateStatus.enabled) {
569
+ return {
570
+ success: false,
571
+ updatesFound: false,
572
+ notificationSent: false,
573
+ error: {
574
+ code: UpdateErrorCode.INVALID_CONFIG,
575
+ message: 'Background updates not enabled',
576
+ },
577
+ };
578
+ }
579
+ this.backgroundUpdateStatus.isRunning = true;
580
+ this.backgroundUpdateStatus.checkCount++;
581
+ this.backgroundUpdateStatus.lastCheckTime = Date.now();
582
+ try {
583
+ const updateInfo = await this.getAppUpdateInfo();
584
+ const liveUpdate = await this.getLatest();
585
+ const updatesFound = updateInfo.updateAvailable || liveUpdate.available;
586
+ let notificationSent = false;
587
+ if (updatesFound) {
588
+ notificationSent = await this.sendWebNotification(updateInfo, liveUpdate);
589
+ }
590
+ this.backgroundUpdateStatus.isRunning = false;
591
+ this.backgroundUpdateStatus.lastUpdateTime = updatesFound
592
+ ? Date.now()
593
+ : undefined;
594
+ this.backgroundUpdateStatus.lastError = undefined;
595
+ return {
596
+ success: true,
597
+ updatesFound,
598
+ appUpdate: updateInfo.updateAvailable ? updateInfo : undefined,
599
+ liveUpdate: liveUpdate.available ? liveUpdate : undefined,
600
+ notificationSent,
601
+ };
602
+ }
603
+ catch (error) {
604
+ this.backgroundUpdateStatus.isRunning = false;
605
+ this.backgroundUpdateStatus.failureCount++;
606
+ this.backgroundUpdateStatus.lastError = {
607
+ code: UpdateErrorCode.UNKNOWN_ERROR,
608
+ message: error instanceof Error ? error.message : 'Unknown error',
609
+ };
610
+ return {
611
+ success: false,
612
+ updatesFound: false,
613
+ notificationSent: false,
614
+ error: this.backgroundUpdateStatus.lastError,
615
+ };
616
+ }
617
+ }
618
+ async setNotificationPreferences(preferences) {
619
+ if (!this.config.backgroundUpdate) {
620
+ this.config.backgroundUpdate = {};
621
+ }
622
+ this.config.backgroundUpdate.notificationPreferences = preferences;
623
+ this.saveConfiguration();
624
+ }
625
+ async getNotificationPermissions() {
626
+ if (!('Notification' in window)) {
627
+ return {
628
+ granted: false,
629
+ canRequest: false,
630
+ };
631
+ }
632
+ const permission = Notification.permission;
633
+ return {
634
+ granted: permission === 'granted',
635
+ canRequest: permission === 'default',
636
+ };
637
+ }
638
+ async requestNotificationPermissions() {
639
+ if (!('Notification' in window)) {
640
+ return false;
641
+ }
642
+ if (Notification.permission === 'granted') {
643
+ return true;
644
+ }
645
+ if (Notification.permission === 'denied') {
646
+ return false;
647
+ }
648
+ const permission = await Notification.requestPermission();
649
+ return permission === 'granted';
650
+ }
651
+ async sendWebNotification(appUpdate, liveUpdate) {
652
+ var _a;
653
+ const permissions = await this.getNotificationPermissions();
654
+ if (!permissions.granted) {
655
+ return false;
656
+ }
657
+ const prefs = (_a = this.config.backgroundUpdate) === null || _a === void 0 ? void 0 : _a.notificationPreferences;
658
+ let title = (prefs === null || prefs === void 0 ? void 0 : prefs.title) || 'App Update Available';
659
+ let body = (prefs === null || prefs === void 0 ? void 0 : prefs.description) || 'A new version of the app is available';
660
+ if (appUpdate.updateAvailable && liveUpdate.available) {
661
+ title = 'App Updates Available';
662
+ body = `App version ${appUpdate.availableVersion} and content updates are available`;
663
+ }
664
+ else if (appUpdate.updateAvailable) {
665
+ title = 'App Update Available';
666
+ body = `Version ${appUpdate.availableVersion} is available`;
667
+ }
668
+ else if (liveUpdate.available) {
669
+ title = 'Content Update Available';
670
+ body = `New content version ${liveUpdate.version} is available`;
671
+ }
672
+ try {
673
+ const notification = new Notification(title, {
674
+ body,
675
+ icon: (prefs === null || prefs === void 0 ? void 0 : prefs.iconName) || '/favicon.ico',
676
+ badge: '/favicon.ico',
677
+ silent: !(prefs === null || prefs === void 0 ? void 0 : prefs.soundEnabled),
678
+ data: {
679
+ type: 'update_available',
680
+ appUpdate,
681
+ liveUpdate,
682
+ },
683
+ });
684
+ notification.onclick = () => {
685
+ window.focus();
686
+ notification.close();
687
+ this.notifyListeners('backgroundUpdateNotification', {
688
+ type: appUpdate.updateAvailable ? 'app_update' : 'live_update',
689
+ updateAvailable: true,
690
+ version: appUpdate.availableVersion || liveUpdate.version,
691
+ action: 'tapped',
692
+ });
693
+ };
694
+ return true;
695
+ }
696
+ catch (error) {
697
+ logger.error('Failed to send notification', error);
698
+ return false;
699
+ }
700
+ }
701
+ /**
702
+ * Helper Methods
703
+ */
704
+ createError(code, message) {
705
+ return {
706
+ code,
707
+ message,
708
+ };
709
+ }
710
+ createDefaultBundle() {
711
+ return {
712
+ bundleId: 'default',
713
+ version: '1.0.0',
714
+ path: '/',
715
+ downloadTime: Date.now(),
716
+ size: 0,
717
+ status: BundleStatus.ACTIVE,
718
+ checksum: '',
719
+ verified: true,
720
+ };
721
+ }
722
+ /**
723
+ * Validate checksum using SHA-256
724
+ * @param data - The data to validate (as string path or ArrayBuffer)
725
+ * @param expectedChecksum - Expected SHA-256 hash (hex string)
726
+ */
727
+ async validateChecksum(data, expectedChecksum) {
728
+ if (!expectedChecksum) {
729
+ throw new Error('Checksum is required but was not provided');
730
+ }
731
+ try {
732
+ let dataBuffer;
733
+ if (typeof data === 'string') {
734
+ // If data is a path/URL, we need to fetch it
735
+ // For local validation, convert string to buffer
736
+ dataBuffer = new TextEncoder().encode(data).buffer;
737
+ }
738
+ else {
739
+ dataBuffer = data;
740
+ }
741
+ // Calculate SHA-256 hash using Web Crypto API
742
+ const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
743
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
744
+ const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
745
+ // Compare checksums (case-insensitive)
746
+ const isValid = hashHex.toLowerCase() === expectedChecksum.toLowerCase();
747
+ if (!isValid) {
748
+ logger.warn('Checksum validation failed', {
749
+ expected: expectedChecksum.toLowerCase(),
750
+ actual: hashHex.toLowerCase(),
751
+ });
752
+ }
753
+ return isValid;
754
+ }
755
+ catch (error) {
756
+ logger.error('Checksum validation error', error);
757
+ return false;
758
+ }
759
+ }
760
+ /**
761
+ * Validate the backend's RSA-SHA256 (PKCS#1 v1.5) signature.
762
+ *
763
+ * Fails closed: if the host app configured a public key or
764
+ * requireSignature, a missing signature throws. Silent-pass was a P0 gap.
765
+ *
766
+ * @param data - The data that was signed (as string path or ArrayBuffer)
767
+ * @param signature - The signature to verify (base64 encoded)
768
+ */
769
+ async validateSignature(data, signature) {
770
+ var _a, _b;
771
+ const publicKeyPem = ((_a = this.config.liveUpdate) === null || _a === void 0 ? void 0 : _a.publicKey) ||
772
+ this.config.publicKey;
773
+ const requireSignature = ((_b = this.config.liveUpdate) === null || _b === void 0 ? void 0 : _b.requireSignature) ||
774
+ this.config.requireSignature === true;
775
+ const signatureRequired = !!publicKeyPem || requireSignature;
776
+ if (!signature) {
777
+ if (signatureRequired) {
778
+ throw new Error('Signature is required but was not provided');
779
+ }
780
+ return true;
781
+ }
782
+ if (!publicKeyPem) {
783
+ throw new Error('Public key not configured for signature validation');
784
+ }
785
+ try {
786
+ let dataBuffer;
787
+ if (typeof data === 'string') {
788
+ dataBuffer = new TextEncoder().encode(data).buffer;
789
+ }
790
+ else {
791
+ dataBuffer = data;
792
+ }
793
+ // Decode base64 signature
794
+ const signatureBuffer = Uint8Array.from(atob(signature), c => c.charCodeAt(0));
795
+ // Import public key
796
+ const publicKey = await this.importPublicKey(publicKeyPem);
797
+ // Verify the RSA-SHA256 signature used by the backend.
798
+ const isValid = await crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, signatureBuffer, dataBuffer);
799
+ if (!isValid) {
800
+ logger.warn('Signature validation failed');
801
+ }
802
+ return isValid;
803
+ }
804
+ catch (error) {
805
+ logger.error('Signature validation error', error);
806
+ return false;
807
+ }
808
+ }
809
+ /**
810
+ * Import RSA public key from PEM format
811
+ */
812
+ async importPublicKey(pem) {
813
+ // Remove PEM headers and decode
814
+ const pemContents = pem
815
+ .replace(/-----BEGIN PUBLIC KEY-----/, '')
816
+ .replace(/-----END PUBLIC KEY-----/, '')
817
+ .replace(/\s/g, '');
818
+ const binaryDer = Uint8Array.from(atob(pemContents), c => c.charCodeAt(0));
819
+ return crypto.subtle.importKey('spki', binaryDer, {
820
+ name: 'RSASSA-PKCS1-v1_5',
821
+ hash: 'SHA-256',
822
+ }, false, ['verify']);
823
+ }
824
+ /**
825
+ * Safe localStorage accessor. Returns `null` in environments where
826
+ * `localStorage` isn't available — SSR, Node-only test runners that
827
+ * stub `window` without storage, or sandboxed iframes. All callers
828
+ * MUST tolerate a `null` return and skip persistence.
829
+ */
830
+ getLocalStorage() {
831
+ try {
832
+ if (typeof window === 'undefined')
833
+ return null;
834
+ if (typeof window.localStorage === 'undefined')
835
+ return null;
836
+ return window.localStorage;
837
+ }
838
+ catch (_a) {
839
+ // Some browsers throw on localStorage access in private mode.
840
+ return null;
841
+ }
842
+ }
843
+ loadStoredData() {
844
+ const storage = this.getLocalStorage();
845
+ if (!storage)
846
+ return;
847
+ // Load configuration — note that any previously-persisted copy was
848
+ // pre-v2 and may contain an apiKey/publicKey in plaintext. We still
849
+ // read it to preserve non-sensitive state (channel, etc.) but secrets
850
+ // are stripped on save; an old cache wipes itself on first save.
851
+ const storedConfig = storage.getItem('native-update-config');
852
+ if (storedConfig) {
853
+ this.config = JSON.parse(storedConfig);
854
+ }
855
+ // Load bundles
856
+ const storedBundles = storage.getItem('native-update-bundles');
857
+ if (storedBundles) {
858
+ const bundlesArray = JSON.parse(storedBundles);
859
+ bundlesArray.forEach((bundle) => this.bundles.set(bundle.bundleId, bundle));
860
+ }
861
+ // Load current bundle
862
+ const storedCurrent = storage.getItem('native-update-current');
863
+ if (storedCurrent) {
864
+ this.currentBundle = JSON.parse(storedCurrent);
865
+ }
866
+ // Load last review request time
867
+ const storedLastReview = storage.getItem('native-update-last-review');
868
+ if (storedLastReview) {
869
+ this.lastReviewRequest = parseInt(storedLastReview, 10);
870
+ }
871
+ // Load launch count
872
+ const storedLaunchCount = storage.getItem('native-update-launch-count');
873
+ if (storedLaunchCount) {
874
+ this.launchCount = parseInt(storedLaunchCount, 10);
875
+ }
876
+ }
877
+ saveStoredData() {
878
+ const storage = this.getLocalStorage();
879
+ if (!storage)
880
+ return;
881
+ storage.setItem('native-update-bundles', JSON.stringify(Array.from(this.bundles.values())));
882
+ if (this.currentBundle) {
883
+ storage.setItem('native-update-current', JSON.stringify(this.currentBundle));
884
+ }
885
+ }
886
+ sanitizeConfigForPersistence(raw) {
887
+ if (!raw || typeof raw !== 'object')
888
+ return raw;
889
+ const clone = JSON.parse(JSON.stringify(raw));
890
+ for (const path of NativeUpdateWeb.SENSITIVE_CONFIG_PATHS) {
891
+ const segments = path.split('.');
892
+ let cursor = clone;
893
+ for (let i = 0; i < segments.length - 1; i++) {
894
+ const next = cursor === null || cursor === void 0 ? void 0 : cursor[segments[i]];
895
+ if (next && typeof next === 'object') {
896
+ cursor = next;
897
+ }
898
+ else {
899
+ cursor = undefined;
900
+ break;
901
+ }
902
+ }
903
+ if (cursor) {
904
+ delete cursor[segments[segments.length - 1]];
905
+ }
906
+ }
907
+ return clone;
908
+ }
909
+ saveConfiguration() {
910
+ var _a;
911
+ (_a = this.getLocalStorage()) === null || _a === void 0 ? void 0 : _a.setItem('native-update-config', JSON.stringify(this.sanitizeConfigForPersistence(this.config)));
912
+ }
913
+ getInstallDate() {
914
+ const storage = this.getLocalStorage();
915
+ const stored = storage === null || storage === void 0 ? void 0 : storage.getItem('native-update-install-date');
916
+ if (stored) {
917
+ return parseInt(stored, 10);
918
+ }
919
+ const now = Date.now();
920
+ storage === null || storage === void 0 ? void 0 : storage.setItem('native-update-install-date', now.toString());
921
+ return now;
922
+ }
923
+ incrementLaunchCount() {
924
+ var _a;
925
+ this.launchCount++;
926
+ (_a = this.getLocalStorage()) === null || _a === void 0 ? void 0 : _a.setItem('native-update-launch-count', this.launchCount.toString());
927
+ }
928
+ /**
929
+ * Get configured review URL from plugin config
930
+ * Returns Play Store, App Store, or custom web review URL based on platform/config
931
+ */
932
+ getConfiguredReviewUrl() {
933
+ var _a;
934
+ // Check for platform-specific store URLs from config
935
+ const storeUrls = (_a = this.config.appUpdate) === null || _a === void 0 ? void 0 : _a.storeUrl;
936
+ // Try to get iOS App Store URL
937
+ if (storeUrls === null || storeUrls === void 0 ? void 0 : storeUrls.ios) {
938
+ return storeUrls.ios;
939
+ }
940
+ // Try to get Android Play Store URL
941
+ if (storeUrls === null || storeUrls === void 0 ? void 0 : storeUrls.android) {
942
+ return storeUrls.android;
943
+ }
944
+ // Try custom web review URL from config (may be in extended config)
945
+ const extendedConfig = this.config;
946
+ const appReviewConfig = this.config.appReview;
947
+ if (appReviewConfig === null || appReviewConfig === void 0 ? void 0 : appReviewConfig.webReviewUrl) {
948
+ return appReviewConfig.webReviewUrl;
949
+ }
950
+ // Try to construct URL from app store IDs
951
+ const appStoreId = extendedConfig.appStoreId;
952
+ if (appStoreId) {
953
+ return `https://apps.apple.com/app/id${appStoreId}?action=write-review`;
954
+ }
955
+ // Check for package name for Play Store
956
+ const packageName = extendedConfig.packageName;
957
+ if (packageName) {
958
+ return `https://play.google.com/store/apps/details?id=${packageName}&showAllReviews=true`;
959
+ }
960
+ // No review URL configured - return null to indicate review not available
961
+ logger.warn('No review URL configured. Set appUpdate.storeUrl.ios, appUpdate.storeUrl.android, ' +
962
+ 'appReview.webReviewUrl, appStoreId, or packageName in plugin config.');
963
+ return null;
964
+ }
965
+ }
966
+ /**
967
+ * Strip secrets before persisting config to localStorage. A browser's
968
+ * localStorage is accessible to any script running in the page (XSS,
969
+ * compromised deps) — an `apiKey` or `publicKey` sitting there is a
970
+ * ready-to-use credential. Host apps must pass these on every
971
+ * `initialize()` call; they are never cached cross-session.
972
+ */
973
+ NativeUpdateWeb.SENSITIVE_CONFIG_PATHS = [
974
+ 'apiKey',
975
+ 'publicKey',
976
+ 'liveUpdate.publicKey',
977
+ 'liveUpdate.apiKey',
978
+ 'security.publicKey',
979
+ ];
980
+ // Alias for backward compatibility with tests
981
+ // Already exported above