native-update-capacitor 0.0.0-stage → 4.3.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 (139) 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/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,361 @@
1
+ import { ConfigManager } from './config';
2
+ import { ValidationError, ErrorCode } from './errors';
3
+ import { Logger } from './logger';
4
+ export class SecurityValidator {
5
+ constructor() {
6
+ this.configManager = ConfigManager.getInstance();
7
+ this.logger = Logger.getInstance();
8
+ }
9
+ static getInstance() {
10
+ if (!SecurityValidator.instance) {
11
+ SecurityValidator.instance = new SecurityValidator();
12
+ }
13
+ return SecurityValidator.instance;
14
+ }
15
+ /**
16
+ * Validate URL is HTTPS
17
+ */
18
+ static validateUrl(url) {
19
+ try {
20
+ const parsed = new URL(url);
21
+ return parsed.protocol === 'https:';
22
+ }
23
+ catch (_a) {
24
+ return false;
25
+ }
26
+ }
27
+ /**
28
+ * Reject any URL that is not HTTPS (or known native-app schemes
29
+ * `market:` / `itms-apps:` for opening the app store). Throws so
30
+ * callers can't silently fall through to a `javascript:` payload.
31
+ */
32
+ static validateDownloadUrl(url) {
33
+ if (!this.validateUrl(url)) {
34
+ throw new ValidationError(ErrorCode.INSECURE_URL, `Refusing non-HTTPS URL: ${url}`);
35
+ }
36
+ }
37
+ /**
38
+ * Validate URL whose only acceptable schemes are HTTPS, `market:` (Play
39
+ * Store), or `itms-apps:` (App Store). Used by `openAppStore`.
40
+ */
41
+ static validateStoreUrl(url) {
42
+ let parsed;
43
+ try {
44
+ parsed = new URL(url);
45
+ }
46
+ catch (_a) {
47
+ throw new ValidationError(ErrorCode.INSECURE_URL, `Invalid URL: ${url}`);
48
+ }
49
+ const allowed = ['https:', 'market:', 'itms-apps:'];
50
+ if (!allowed.includes(parsed.protocol)) {
51
+ throw new ValidationError(ErrorCode.INSECURE_URL, `Refusing URL scheme ${parsed.protocol}`);
52
+ }
53
+ }
54
+ /**
55
+ * Validate checksum format
56
+ */
57
+ static validateChecksum(checksum) {
58
+ return /^[a-f0-9]{64}$/i.test(checksum);
59
+ }
60
+ /**
61
+ * Sanitize input string
62
+ */
63
+ static sanitizeInput(input) {
64
+ if (!input)
65
+ return '';
66
+ return input.replace(/<[^>]*>/g, '').replace(/[^\w\s/.-]/g, '');
67
+ }
68
+ /**
69
+ * Validate bundle size
70
+ */
71
+ static validateBundleSize(size) {
72
+ const MAX_SIZE = 100 * 1024 * 1024; // 100MB
73
+ return size > 0 && size <= MAX_SIZE;
74
+ }
75
+ /**
76
+ * Calculate SHA-256 checksum of data
77
+ */
78
+ async calculateChecksum(data) {
79
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
80
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
81
+ return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
82
+ }
83
+ /**
84
+ * Verify checksum matches expected value.
85
+ * Fails closed when a checksum is required but missing. Only a configuration
86
+ * that explicitly disables signature+HTTPS enforcement AND omits the
87
+ * checksum will skip verification — OTA code paths must always pass one.
88
+ */
89
+ async verifyChecksum(data, expectedChecksum) {
90
+ if (!expectedChecksum) {
91
+ throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Checksum is required but was not provided');
92
+ }
93
+ const actualChecksum = await this.calculateChecksum(data);
94
+ const isValid = actualChecksum === expectedChecksum.toLowerCase();
95
+ if (!isValid) {
96
+ this.logger.error('Checksum verification failed', {
97
+ expected: expectedChecksum,
98
+ actual: actualChecksum,
99
+ });
100
+ }
101
+ return isValid;
102
+ }
103
+ /**
104
+ * Alias for verifyChecksum for backward compatibility
105
+ */
106
+ async validateChecksum(data, expectedChecksum) {
107
+ return this.verifyChecksum(data, expectedChecksum);
108
+ }
109
+ /**
110
+ * Verify digital signature using Web Crypto API.
111
+ *
112
+ * Fails closed: if signature verification is enabled (the default), any of
113
+ * `publicKey`, `enableSignatureValidation`, or `requireSignature` being set
114
+ * makes a signature mandatory. A missing signature in that state throws —
115
+ * never silently returns true. Silent-pass was a P0 gap in prior releases.
116
+ */
117
+ async verifySignature(data, signature) {
118
+ const enabled = this.configManager.get('enableSignatureValidation');
119
+ const requireSignature = this.configManager.get('requireSignature');
120
+ const publicKey = this.configManager.get('publicKey');
121
+ const signatureRequired = enabled || requireSignature || !!publicKey;
122
+ if (!signature) {
123
+ if (signatureRequired) {
124
+ throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Signature is required but was not provided');
125
+ }
126
+ return true;
127
+ }
128
+ if (!publicKey) {
129
+ throw new ValidationError(ErrorCode.SIGNATURE_INVALID, 'Public key not configured for signature validation');
130
+ }
131
+ try {
132
+ // Import public key
133
+ const cryptoKey = await crypto.subtle.importKey('spki', this.pemToArrayBuffer(publicKey), {
134
+ name: 'RSASSA-PKCS1-v1_5',
135
+ hash: 'SHA-256',
136
+ }, false, ['verify']);
137
+ // Verify signature
138
+ const isValid = await crypto.subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, cryptoKey, this.base64ToArrayBuffer(signature), data);
139
+ if (!isValid) {
140
+ this.logger.error('Signature verification failed');
141
+ }
142
+ return isValid;
143
+ }
144
+ catch (error) {
145
+ this.logger.error('Signature verification error', error);
146
+ return false;
147
+ }
148
+ }
149
+ /**
150
+ * Convert PEM to ArrayBuffer
151
+ */
152
+ pemToArrayBuffer(pem) {
153
+ const base64 = pem
154
+ .replace(/-----BEGIN PUBLIC KEY-----/g, '')
155
+ .replace(/-----END PUBLIC KEY-----/g, '')
156
+ .replace(/\s/g, '');
157
+ return this.base64ToArrayBuffer(base64);
158
+ }
159
+ /**
160
+ * Convert base64 to ArrayBuffer
161
+ */
162
+ base64ToArrayBuffer(base64) {
163
+ const binaryString = atob(base64);
164
+ const bytes = new Uint8Array(binaryString.length);
165
+ for (let i = 0; i < binaryString.length; i++) {
166
+ bytes[i] = binaryString.charCodeAt(i);
167
+ }
168
+ return bytes.buffer;
169
+ }
170
+ /**
171
+ * Sanitize file path to prevent directory traversal
172
+ */
173
+ sanitizePath(path) {
174
+ // Remove any parent directory references
175
+ const sanitized = path
176
+ .split('/')
177
+ .filter((part) => part !== '..' && part !== '.')
178
+ .join('/');
179
+ // Ensure path doesn't start with /
180
+ return sanitized.replace(/^\/+/, '');
181
+ }
182
+ /**
183
+ * Validate bundle ID format
184
+ */
185
+ validateBundleId(bundleId) {
186
+ if (!bundleId || typeof bundleId !== 'string') {
187
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID must be a non-empty string');
188
+ }
189
+ // Allow alphanumeric, hyphens, underscores, and dots
190
+ const validPattern = /^[a-zA-Z0-9\-_.]+$/;
191
+ if (!validPattern.test(bundleId)) {
192
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID contains invalid characters');
193
+ }
194
+ if (bundleId.length > 100) {
195
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is too long (max 100 characters)');
196
+ }
197
+ }
198
+ /**
199
+ * Validate semantic version format
200
+ */
201
+ validateVersion(version) {
202
+ if (!version || typeof version !== 'string') {
203
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must be a non-empty string');
204
+ }
205
+ // Basic semantic versioning pattern
206
+ const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
207
+ if (!semverPattern.test(version)) {
208
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Version must follow semantic versioning format (e.g., 1.2.3)');
209
+ }
210
+ }
211
+ /**
212
+ * Check if version is a downgrade
213
+ */
214
+ isVersionDowngrade(currentVersion, newVersion) {
215
+ const current = this.parseVersion(currentVersion);
216
+ const next = this.parseVersion(newVersion);
217
+ if (next.major < current.major)
218
+ return true;
219
+ if (next.major > current.major)
220
+ return false;
221
+ if (next.minor < current.minor)
222
+ return true;
223
+ if (next.minor > current.minor)
224
+ return false;
225
+ return next.patch < current.patch;
226
+ }
227
+ /**
228
+ * Parse semantic version
229
+ */
230
+ parseVersion(version) {
231
+ const parts = version.split('-')[0].split('.'); // Ignore pre-release
232
+ return {
233
+ major: parseInt(parts[0], 10) || 0,
234
+ minor: parseInt(parts[1], 10) || 0,
235
+ patch: parseInt(parts[2], 10) || 0,
236
+ };
237
+ }
238
+ /**
239
+ * Validate URL format and security
240
+ */
241
+ validateUrl(url) {
242
+ if (!url || typeof url !== 'string') {
243
+ throw new ValidationError(ErrorCode.INVALID_URL, 'URL must be a non-empty string');
244
+ }
245
+ let parsedUrl;
246
+ try {
247
+ parsedUrl = new URL(url);
248
+ }
249
+ catch (_a) {
250
+ throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');
251
+ }
252
+ // Enforce HTTPS
253
+ if (parsedUrl.protocol !== 'https:') {
254
+ throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed');
255
+ }
256
+ // Check against allowed hosts
257
+ const allowedHosts = this.configManager.get('allowedHosts');
258
+ if (allowedHosts.length > 0 && !allowedHosts.includes(parsedUrl.hostname)) {
259
+ throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);
260
+ }
261
+ // Prevent localhost/private IPs in production
262
+ const privatePatterns = [
263
+ /^localhost$/i,
264
+ /^127\./,
265
+ /^10\./,
266
+ /^172\.(1[6-9]|2[0-9]|3[0-1])\./,
267
+ /^192\.168\./,
268
+ /^::1$/,
269
+ /^fc00:/i,
270
+ /^fe80:/i,
271
+ ];
272
+ if (privatePatterns.some((pattern) => pattern.test(parsedUrl.hostname))) {
273
+ throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, 'Private/local addresses are not allowed');
274
+ }
275
+ }
276
+ /**
277
+ * Validate file size
278
+ */
279
+ validateFileSize(size) {
280
+ if (typeof size !== 'number' || size < 0) {
281
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'File size must be a non-negative number');
282
+ }
283
+ const maxSize = this.configManager.get('maxBundleSize');
284
+ if (size > maxSize) {
285
+ throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${size} exceeds maximum allowed size of ${maxSize} bytes`);
286
+ }
287
+ }
288
+ /**
289
+ * Generate a secure random ID
290
+ */
291
+ generateSecureId() {
292
+ const array = new Uint8Array(16);
293
+ crypto.getRandomValues(array);
294
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');
295
+ }
296
+ /**
297
+ * Validate certificate pinning for HTTPS connections
298
+ *
299
+ * Web Implementation Note:
300
+ * Certificate pinning at the TLS level is NOT possible in web browsers for security reasons.
301
+ * However, this implementation provides signature verification which serves a similar purpose:
302
+ * - Validates server identity through cryptographic signatures
303
+ * - Prevents MITM attacks via signature validation
304
+ * - Uses SHA-256 certificate fingerprints for validation
305
+ *
306
+ * For native platforms (iOS/Android), full TLS certificate pinning is implemented
307
+ * in the native layers using platform-specific APIs (URLSessionDelegate, OkHttp).
308
+ *
309
+ * This web implementation is production-ready and provides equivalent security
310
+ * through the signature verification system.
311
+ */
312
+ async validateCertificatePin(hostname, certificate) {
313
+ const certificatePins = this.configManager.certificatePins;
314
+ if (!certificatePins ||
315
+ !Array.isArray(certificatePins) ||
316
+ certificatePins.length === 0) {
317
+ // No pins configured, allow connection
318
+ return true;
319
+ }
320
+ const hostPins = certificatePins.filter((pin) => pin.hostname === hostname);
321
+ if (hostPins.length === 0) {
322
+ // No pins for this host, allow connection
323
+ return true;
324
+ }
325
+ // Check if certificate matches any of the pins
326
+ const certificateHash = await this.calculateCertificateHash(certificate);
327
+ const isValid = hostPins.some((pin) => pin.sha256 === certificateHash);
328
+ if (!isValid) {
329
+ this.logger.error('Certificate pinning validation failed', {
330
+ hostname,
331
+ expectedPins: hostPins.map((p) => p.sha256),
332
+ actualHash: certificateHash,
333
+ });
334
+ }
335
+ return isValid;
336
+ }
337
+ /**
338
+ * Calculate SHA-256 hash of certificate
339
+ */
340
+ async calculateCertificateHash(certificate) {
341
+ const encoder = new TextEncoder();
342
+ const data = encoder.encode(certificate);
343
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
344
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
345
+ return 'sha256/' + btoa(String.fromCharCode(...hashArray));
346
+ }
347
+ /**
348
+ * Validate metadata object
349
+ */
350
+ validateMetadata(metadata) {
351
+ if (metadata && typeof metadata !== 'object') {
352
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata must be an object');
353
+ }
354
+ // Limit metadata size to prevent abuse
355
+ const metadataStr = JSON.stringify(metadata || {});
356
+ if (metadataStr.length > 10240) {
357
+ // 10KB limit
358
+ throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Metadata is too large (max 10KB)');
359
+ }
360
+ }
361
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Single source of truth for the Native Update backend update-check
3
+ * contract.
4
+ *
5
+ * Every "does the Laravel backend have a newer bundle for me?" call in the
6
+ * plugin funnels through {@link checkForUpdate} so the wire shape — path,
7
+ * headers, query, and response fields — is defined in exactly one place.
8
+ * Before this helper existed, three modules each rolled their own request
9
+ * against paths the backend does not serve (`/check`, `/updates/latest`),
10
+ * so background + version-manager update checks silently never worked.
11
+ *
12
+ * ## Wire contract (implemented by `UpdateController@check` in the backend)
13
+ *
14
+ * ```
15
+ * GET {baseUrl}/v1/updates/check?channel={channel}
16
+ * X-API-Key: nu_app_… (required; ValidateApiKey middleware → 401 without it)
17
+ * X-Device-ID: stable per-device hash (required; 400 without it)
18
+ * X-Current-Version: the currently-installed bundle version
19
+ * X-Platform: ios | android | web
20
+ * X-App-Version: native app version (optional)
21
+ * X-Client-Sdk: capacitor (the server then offers only `web_bundle` builds)
22
+ * X-Sdk-Version: this plugin's version (SDK_VERSION)
23
+ * X-Android-Package: applicationId (optional; sent when identity.platform === 'android')
24
+ * X-Android-Cert-Sha256: signing cert SHA-256, hex (optional)
25
+ * X-Android-Cert-Sha1: signing cert SHA-1, hex (optional)
26
+ * X-Ios-Bundle-Id: bundle identifier (optional; sent when identity.platform === 'ios')
27
+ * X-Ios-Team-Id: team id (optional; currently never populated)
28
+ * ```
29
+ *
30
+ * The X-Android-* / X-Ios-* headers carry the app's client identity for
31
+ * per-key client restrictions (see AppIdentity + `getAppIdentity()`). They are
32
+ * only attached when a matching `identity` is supplied; web clients identify
33
+ * via the browser-enforced Origin header instead.
34
+ *
35
+ * Response (200):
36
+ * ```jsonc
37
+ * // no update:
38
+ * { "available": false, "message": "…" }
39
+ * // update available:
40
+ * {
41
+ * "available": true,
42
+ * "version": "1.2.3",
43
+ * "bundleId": "…uuid…",
44
+ * "downloadUrl": "https://…signed…",
45
+ * "checksum": "…sha256…",
46
+ * "signature": "…|null",
47
+ * "size": 123456,
48
+ * "mandatory": false,
49
+ * "releaseNotes": "…|null",
50
+ * "minNativeVersion": "…|null",
51
+ * "expiresAt": "ISO-8601"
52
+ * }
53
+ * ```
54
+ *
55
+ * Custom backends must return these exact field names — see
56
+ * `docs/server-requirements.md`.
57
+ */
58
+ import type { AppIdentity } from '../types/app-identity';
59
+ /**
60
+ * This plugin's version, sent as `X-Sdk-Version`. Kept equal to package.json (and to the Kotlin and Swift
61
+ * constants) by tests/sdk-version.test.ts.
62
+ */
63
+ export declare const SDK_VERSION = "4.3.0";
64
+ /** Request inputs for a single backend update check. */
65
+ export interface UpdateCheckRequest {
66
+ /** API key issued by the dashboard; sent as `X-API-Key`. Required. */
67
+ apiKey: string;
68
+ /** Release channel (`production` | `staging` | `development`). */
69
+ channel: string;
70
+ /** Currently-installed bundle version; sent as `X-Current-Version`. */
71
+ currentVersion: string;
72
+ /** Stable device identifier; sent as `X-Device-ID`. Required by the backend. */
73
+ deviceId: string;
74
+ /** Device platform (`ios` | `android` | `web`); sent as `X-Platform`. */
75
+ platform: string;
76
+ /** Native app version; sent as `X-App-Version` when present. */
77
+ appVersion?: string;
78
+ /**
79
+ * App client identity for API-key client restrictions. When present and its
80
+ * `platform` is `android`/`ios`, the matching `X-Android-*` / `X-Ios-*`
81
+ * headers are attached. Web clients omit it (the Origin header identifies
82
+ * them). Obtain it from `NativeUpdate.getAppIdentity()`.
83
+ */
84
+ identity?: AppIdentity;
85
+ /** Optional abort signal so callers can time the request out. */
86
+ signal?: AbortSignal;
87
+ }
88
+ /**
89
+ * Normalized response from `GET {baseUrl}/v1/updates/check`. Field names
90
+ * mirror the backend JSON verbatim (already camelCase on the wire).
91
+ */
92
+ export interface BackendUpdateCheckResponse {
93
+ available: boolean;
94
+ version?: string;
95
+ bundleId?: string;
96
+ downloadUrl?: string;
97
+ checksum?: string;
98
+ signature?: string | null;
99
+ signatureAlgorithm?: 'RSA-SHA256' | null;
100
+ delta?: import('../definitions').DeltaUpdateInfo | null;
101
+ size?: number;
102
+ mandatory?: boolean;
103
+ releaseNotes?: string | null;
104
+ minNativeVersion?: string | null;
105
+ expiresAt?: string;
106
+ /** `web_bundle` for every build this client is offered (the server filters by X-Client-Sdk). */
107
+ payloadType?: 'web_bundle' | 'assets';
108
+ message?: string;
109
+ /** Billing hold: a newer release exists but is not served (see `CheckForUpdateResult.held`). */
110
+ held?: boolean;
111
+ code?: string;
112
+ }
113
+ /**
114
+ * Perform one update check against the Native Update backend.
115
+ *
116
+ * Returns `{ available: false }` for any non-2xx response (the backend
117
+ * uses 200 for "no update" and reserves 4xx for auth/validation failures,
118
+ * which are non-actionable for an update check). Network failures reject —
119
+ * callers decide whether to swallow or surface them.
120
+ */
121
+ export declare function checkForUpdate(baseUrl: string, req: UpdateCheckRequest): Promise<BackendUpdateCheckResponse>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Single source of truth for the Native Update backend update-check
3
+ * contract.
4
+ *
5
+ * Every "does the Laravel backend have a newer bundle for me?" call in the
6
+ * plugin funnels through {@link checkForUpdate} so the wire shape — path,
7
+ * headers, query, and response fields — is defined in exactly one place.
8
+ * Before this helper existed, three modules each rolled their own request
9
+ * against paths the backend does not serve (`/check`, `/updates/latest`),
10
+ * so background + version-manager update checks silently never worked.
11
+ *
12
+ * ## Wire contract (implemented by `UpdateController@check` in the backend)
13
+ *
14
+ * ```
15
+ * GET {baseUrl}/v1/updates/check?channel={channel}
16
+ * X-API-Key: nu_app_… (required; ValidateApiKey middleware → 401 without it)
17
+ * X-Device-ID: stable per-device hash (required; 400 without it)
18
+ * X-Current-Version: the currently-installed bundle version
19
+ * X-Platform: ios | android | web
20
+ * X-App-Version: native app version (optional)
21
+ * X-Client-Sdk: capacitor (the server then offers only `web_bundle` builds)
22
+ * X-Sdk-Version: this plugin's version (SDK_VERSION)
23
+ * X-Android-Package: applicationId (optional; sent when identity.platform === 'android')
24
+ * X-Android-Cert-Sha256: signing cert SHA-256, hex (optional)
25
+ * X-Android-Cert-Sha1: signing cert SHA-1, hex (optional)
26
+ * X-Ios-Bundle-Id: bundle identifier (optional; sent when identity.platform === 'ios')
27
+ * X-Ios-Team-Id: team id (optional; currently never populated)
28
+ * ```
29
+ *
30
+ * The X-Android-* / X-Ios-* headers carry the app's client identity for
31
+ * per-key client restrictions (see AppIdentity + `getAppIdentity()`). They are
32
+ * only attached when a matching `identity` is supplied; web clients identify
33
+ * via the browser-enforced Origin header instead.
34
+ *
35
+ * Response (200):
36
+ * ```jsonc
37
+ * // no update:
38
+ * { "available": false, "message": "…" }
39
+ * // update available:
40
+ * {
41
+ * "available": true,
42
+ * "version": "1.2.3",
43
+ * "bundleId": "…uuid…",
44
+ * "downloadUrl": "https://…signed…",
45
+ * "checksum": "…sha256…",
46
+ * "signature": "…|null",
47
+ * "size": 123456,
48
+ * "mandatory": false,
49
+ * "releaseNotes": "…|null",
50
+ * "minNativeVersion": "…|null",
51
+ * "expiresAt": "ISO-8601"
52
+ * }
53
+ * ```
54
+ *
55
+ * Custom backends must return these exact field names — see
56
+ * `docs/server-requirements.md`.
57
+ */
58
+ /**
59
+ * This plugin's version, sent as `X-Sdk-Version`. Kept equal to package.json (and to the Kotlin and Swift
60
+ * constants) by tests/sdk-version.test.ts.
61
+ */
62
+ export const SDK_VERSION = '4.3.0';
63
+ /**
64
+ * Perform one update check against the Native Update backend.
65
+ *
66
+ * Returns `{ available: false }` for any non-2xx response (the backend
67
+ * uses 200 for "no update" and reserves 4xx for auth/validation failures,
68
+ * which are non-actionable for an update check). Network failures reject —
69
+ * callers decide whether to swallow or surface them.
70
+ */
71
+ export async function checkForUpdate(baseUrl, req) {
72
+ var _a, _b, _c, _d, _e;
73
+ const url = `${baseUrl.replace(/\/$/, '')}/v1/updates/check?channel=${encodeURIComponent(req.channel)}`;
74
+ const headers = {
75
+ 'Content-Type': 'application/json',
76
+ 'X-API-Key': req.apiKey,
77
+ 'X-Device-ID': req.deviceId,
78
+ 'X-Current-Version': req.currentVersion,
79
+ 'X-Platform': req.platform,
80
+ 'X-Client-Sdk': 'capacitor',
81
+ 'X-Sdk-Version': SDK_VERSION,
82
+ };
83
+ if (req.appVersion) {
84
+ headers['X-App-Version'] = req.appVersion;
85
+ }
86
+ // App client-identity headers for per-key client restrictions. Only attached
87
+ // for native platforms; web clients identify via the browser Origin header.
88
+ const identity = req.identity;
89
+ if ((identity === null || identity === void 0 ? void 0 : identity.platform) === 'android') {
90
+ if (identity.packageName)
91
+ headers['X-Android-Package'] = identity.packageName;
92
+ if (identity.certSha256)
93
+ headers['X-Android-Cert-Sha256'] = identity.certSha256;
94
+ if (identity.certSha1)
95
+ headers['X-Android-Cert-Sha1'] = identity.certSha1;
96
+ }
97
+ else if ((identity === null || identity === void 0 ? void 0 : identity.platform) === 'ios') {
98
+ if (identity.bundleId)
99
+ headers['X-Ios-Bundle-Id'] = identity.bundleId;
100
+ if (identity.teamId)
101
+ headers['X-Ios-Team-Id'] = identity.teamId;
102
+ }
103
+ const response = await fetch(url, { method: 'GET', headers, signal: req.signal });
104
+ if (!response.ok) {
105
+ return { available: false };
106
+ }
107
+ const data = (await response.json());
108
+ return {
109
+ available: Boolean(data.available),
110
+ version: data.version,
111
+ bundleId: data.bundleId,
112
+ downloadUrl: data.downloadUrl,
113
+ checksum: data.checksum,
114
+ signature: (_a = data.signature) !== null && _a !== void 0 ? _a : undefined,
115
+ signatureAlgorithm: (_b = data.signatureAlgorithm) !== null && _b !== void 0 ? _b : undefined,
116
+ delta: (_c = data.delta) !== null && _c !== void 0 ? _c : undefined,
117
+ size: data.size,
118
+ mandatory: data.mandatory,
119
+ releaseNotes: (_d = data.releaseNotes) !== null && _d !== void 0 ? _d : undefined,
120
+ minNativeVersion: (_e = data.minNativeVersion) !== null && _e !== void 0 ? _e : undefined,
121
+ expiresAt: data.expiresAt,
122
+ payloadType: data.payloadType,
123
+ message: data.message,
124
+ held: data.held === true ? true : undefined,
125
+ code: data.code,
126
+ };
127
+ }