@capgo/capacitor-updater 8.52.1-beta.pr937.1951.1 → 8.53.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 (65) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -2
  2. package/Package.swift +0 -5
  3. package/README.md +199 -67
  4. package/android/build.gradle +9 -88
  5. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +60 -32
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +246 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +45 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +5539 -1066
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +3754 -494
  11. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +496 -0
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +56 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +14 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +6 -23
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1541 -0
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +258 -0
  19. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +45 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +1 -6
  22. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +417 -217
  24. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +1 -3
  25. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  26. package/dist/docs.json +379 -28
  27. package/dist/esm/definitions.d.ts +209 -10
  28. package/dist/esm/definitions.js.map +1 -1
  29. package/dist/plugin.cjs.js.map +1 -1
  30. package/dist/plugin.js.map +1 -1
  31. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  32. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  33. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  34. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  35. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5247 -199
  36. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  37. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +3878 -365
  38. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +328 -0
  39. package/ios/Sources/CapacitorUpdaterPlugin/DelayCondition.swift +74 -0
  40. package/ios/Sources/CapacitorUpdaterPlugin/DelayUntilNext.swift +30 -0
  41. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  42. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +471 -0
  43. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  44. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  45. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  46. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +221 -63
  47. package/ios/Sources/CapacitorUpdaterPlugin/UserDefaultsExtension.swift +46 -0
  48. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +147 -5
  49. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  50. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  51. package/package.json +15 -19
  52. package/android/consumer-rules.pro +0 -15
  53. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCore.java +0 -67
  54. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCoreNative.java +0 -97
  55. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoDownloadWorker.java +0 -188
  56. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngine.java +0 -114
  57. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHolder.java +0 -59
  58. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHost.java +0 -118
  59. package/android/src/main/java/ee/forgr/capacitor_updater/EngineMethodLanes.java +0 -168
  60. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+AppStore.swift +0 -171
  61. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Methods.swift +0 -168
  62. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Overlays.swift +0 -285
  63. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+WebView.swift +0 -134
  64. package/ios/Sources/CapacitorUpdaterPlugin/CapgoCore.swift +0 -61
  65. package/ios/Sources/CapacitorUpdaterPlugin/CapgoEngine.swift +0 -319
@@ -0,0 +1,496 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ /**
10
+ * Created by Awesometic
11
+ * It's encrypt returns Base64 encoded, and also decrypt for Base64 encoded cipher
12
+ * references: http://stackoverflow.com/questions/12471999/rsa-encryption-decryption-in-android
13
+ */
14
+ import android.util.Base64;
15
+ import java.io.File;
16
+ import java.io.FileInputStream;
17
+ import java.io.FileOutputStream;
18
+ import java.io.IOException;
19
+ import java.io.InputStream;
20
+ import java.security.GeneralSecurityException;
21
+ import java.security.InvalidAlgorithmParameterException;
22
+ import java.security.InvalidKeyException;
23
+ import java.security.KeyFactory;
24
+ import java.security.MessageDigest;
25
+ import java.security.NoSuchAlgorithmException;
26
+ import java.security.PublicKey;
27
+ import java.security.spec.InvalidKeySpecException;
28
+ import java.security.spec.X509EncodedKeySpec;
29
+ import javax.crypto.BadPaddingException;
30
+ import javax.crypto.Cipher;
31
+ import javax.crypto.IllegalBlockSizeException;
32
+ import javax.crypto.NoSuchPaddingException;
33
+ import javax.crypto.SecretKey;
34
+ import javax.crypto.spec.IvParameterSpec;
35
+ import javax.crypto.spec.SecretKeySpec;
36
+
37
+ public class CryptoCipher {
38
+
39
+ private static Logger logger;
40
+
41
+ public static void setLogger(Logger loggerInstance) {
42
+ logger = loggerInstance;
43
+ }
44
+
45
+ public static byte[] decryptRSA(byte[] source, PublicKey publicKey)
46
+ throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
47
+ Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
48
+ cipher.init(Cipher.DECRYPT_MODE, publicKey);
49
+ byte[] decryptedBytes = cipher.doFinal(source);
50
+ return decryptedBytes;
51
+ }
52
+
53
+ public static byte[] decryptAES(byte[] cipherText, SecretKey key, byte[] iv) throws GeneralSecurityException {
54
+ if (key == null || iv == null) {
55
+ throw new IllegalArgumentException("AES key and IV must not be null");
56
+ }
57
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
58
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
59
+ SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
60
+ cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
61
+ return cipher.doFinal(cipherText);
62
+ }
63
+
64
+ public static SecretKey byteToSessionKey(byte[] sessionKey) {
65
+ // rebuild key using SecretKeySpec
66
+ return new SecretKeySpec(sessionKey, 0, sessionKey.length, "AES");
67
+ }
68
+
69
+ private static PublicKey readX509PublicKey(byte[] x509Bytes) throws GeneralSecurityException {
70
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA");
71
+ X509EncodedKeySpec keySpec = new X509EncodedKeySpec(x509Bytes);
72
+ try {
73
+ return keyFactory.generatePublic(keySpec);
74
+ } catch (InvalidKeySpecException e) {
75
+ throw new IllegalArgumentException("Unexpected key format!", e);
76
+ }
77
+ }
78
+
79
+ public static PublicKey stringToPublicKey(String public_key) throws GeneralSecurityException {
80
+ String pkcs1Pem = public_key
81
+ .replaceAll("\\s+", "")
82
+ .replace("-----BEGINRSAPUBLICKEY-----", "")
83
+ .replace("-----ENDRSAPUBLICKEY-----", "");
84
+
85
+ byte[] pkcs1EncodedBytes = Base64.decode(pkcs1Pem, Base64.DEFAULT);
86
+ return readPkcs1PublicKey(pkcs1EncodedBytes);
87
+ }
88
+
89
+ // since the public key is in pkcs1 format, we have to convert it to x509 format similar
90
+ // to what needs done with the private key converting to pkcs8 format
91
+ // so, the rest of the code below here is adapted from here https://stackoverflow.com/a/54246646
92
+ private static final int SEQUENCE_TAG = 0x30;
93
+ private static final int BIT_STRING_TAG = 0x03;
94
+ private static final byte[] NO_UNUSED_BITS = new byte[] { 0x00 };
95
+ private static final byte[] RSA_ALGORITHM_IDENTIFIER_SEQUENCE = {
96
+ (byte) 0x30,
97
+ (byte) 0x0d,
98
+ (byte) 0x06,
99
+ (byte) 0x09,
100
+ (byte) 0x2a,
101
+ (byte) 0x86,
102
+ (byte) 0x48,
103
+ (byte) 0x86,
104
+ (byte) 0xf7,
105
+ (byte) 0x0d,
106
+ (byte) 0x01,
107
+ (byte) 0x01,
108
+ (byte) 0x01,
109
+ (byte) 0x05,
110
+ (byte) 0x00
111
+ };
112
+
113
+ private static PublicKey readPkcs1PublicKey(byte[] pkcs1Bytes)
114
+ throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException {
115
+ // convert the pkcs1 public key to an x509 favorable format
116
+ byte[] keyBitString = createDEREncoding(BIT_STRING_TAG, joinPublic(NO_UNUSED_BITS, pkcs1Bytes));
117
+ byte[] keyInfoValue = joinPublic(RSA_ALGORITHM_IDENTIFIER_SEQUENCE, keyBitString);
118
+ byte[] keyInfoSequence = createDEREncoding(SEQUENCE_TAG, keyInfoValue);
119
+ return readX509PublicKey(keyInfoSequence);
120
+ }
121
+
122
+ private static byte[] joinPublic(byte[]... bas) {
123
+ int len = 0;
124
+ for (int i = 0; i < bas.length; i++) {
125
+ len += bas[i].length;
126
+ }
127
+
128
+ byte[] buf = new byte[len];
129
+ int off = 0;
130
+ for (int i = 0; i < bas.length; i++) {
131
+ System.arraycopy(bas[i], 0, buf, off, bas[i].length);
132
+ off += bas[i].length;
133
+ }
134
+
135
+ return buf;
136
+ }
137
+
138
+ public static boolean isValidSessionKey(final String sessionKey) {
139
+ if (sessionKey == null || sessionKey.isEmpty()) {
140
+ return false;
141
+ }
142
+ String[] sessionKeyParts = sessionKey.split(":", -1);
143
+ return sessionKeyParts.length == 2 && !sessionKeyParts[0].isEmpty() && !sessionKeyParts[1].isEmpty();
144
+ }
145
+
146
+ public static void decryptFile(final File file, final String publicKey, final String ivSessionKey) throws IOException {
147
+ if (publicKey.isEmpty() || !isValidSessionKey(ivSessionKey)) {
148
+ if (logger != null) {
149
+ logger.info("Encryption not set, no public key or session, ignored");
150
+ }
151
+ return;
152
+ }
153
+ // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
154
+ if (!publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
155
+ if (logger != null) {
156
+ logger.error("The public key is not a valid RSA Public key");
157
+ }
158
+ throw new IOException("AES file decryption failed: the public key is not a valid RSA public key");
159
+ }
160
+
161
+ try {
162
+ String ivB64 = ivSessionKey.split(":")[0];
163
+ String sessionKeyB64 = ivSessionKey.split(":")[1];
164
+ byte[] iv = Base64.decode(ivB64.getBytes(), Base64.DEFAULT);
165
+ byte[] sessionKey = Base64.decode(sessionKeyB64.getBytes(), Base64.DEFAULT);
166
+ if (iv.length != 16) {
167
+ throw new IOException("AES file decryption failed: IV must be 16 bytes");
168
+ }
169
+ PublicKey pKey = CryptoCipher.stringToPublicKey(publicKey);
170
+ byte[] decryptedSessionKey = CryptoCipher.decryptRSA(sessionKey, pKey);
171
+ if (decryptedSessionKey == null || decryptedSessionKey.length != 16) {
172
+ throw new IOException("AES file decryption failed: decrypted session key must be 16 bytes");
173
+ }
174
+
175
+ SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
176
+ decryptAesFile(file, sKey, iv);
177
+ } catch (GeneralSecurityException e) {
178
+ if (logger != null) {
179
+ logger.info("decryptFile fail");
180
+ }
181
+ throw new IOException("AES file decryption failed: " + e.getMessage(), e);
182
+ }
183
+ }
184
+
185
+ static void decryptAesFile(File file, SecretKey key, byte[] iv) throws IOException {
186
+ if (key == null) {
187
+ throw new IOException("AES file decryption failed: missing session key");
188
+ }
189
+ if (iv == null) {
190
+ throw new IOException("AES file decryption failed: missing IV");
191
+ }
192
+ if (iv.length != 16) {
193
+ throw new IOException("AES file decryption failed: IV must be 16 bytes");
194
+ }
195
+ byte[] keyBytes = key.getEncoded();
196
+ if (keyBytes == null || keyBytes.length != 16) {
197
+ throw new IOException("AES file decryption failed: session key must be 16 bytes");
198
+ }
199
+ if (file.length() == 0) {
200
+ throw new IOException("Empty encrypted data");
201
+ }
202
+ File parent = file.getAbsoluteFile().getParentFile();
203
+ if (parent == null) {
204
+ throw new IOException("Cannot create temp file for " + file.getAbsolutePath());
205
+ }
206
+ File tempFile = File.createTempFile("capgo-aes-", ".tmp", parent);
207
+ try {
208
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
209
+ cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(iv));
210
+ byte[] inBuf = new byte[ioBufferBytes()];
211
+ // Reuse one output buffer. cipher.update(in) allocates a new byte[] per chunk.
212
+ byte[] outBuf = new byte[inBuf.length + 16];
213
+ try (FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(tempFile)) {
214
+ int n;
215
+ while ((n = fis.read(inBuf)) != -1) {
216
+ int outLen = cipher.update(inBuf, 0, n, outBuf, 0);
217
+ if (outLen > 0) {
218
+ fos.write(outBuf, 0, outLen);
219
+ }
220
+ }
221
+ int last = cipher.doFinal(outBuf, 0);
222
+ if (last > 0) {
223
+ fos.write(outBuf, 0, last);
224
+ }
225
+ }
226
+ if (tempFile.length() == 0) {
227
+ throw new IOException("Empty decrypted data");
228
+ }
229
+ replaceFile(tempFile, file);
230
+ tempFile = null;
231
+ } catch (GeneralSecurityException e) {
232
+ throw new IOException("AES file decryption failed: " + e.getMessage(), e);
233
+ } finally {
234
+ if (tempFile != null && tempFile.exists()) {
235
+ tempFile.delete();
236
+ }
237
+ }
238
+ }
239
+
240
+ static void replaceFile(File from, File to) throws IOException {
241
+ if (from.renameTo(to)) {
242
+ return;
243
+ }
244
+ throw new IOException("Failed to replace file: " + to.getAbsolutePath());
245
+ }
246
+
247
+ private static byte[] hexStringToByteArray(String s) {
248
+ int len = s.length();
249
+ byte[] data = new byte[len / 2];
250
+ for (int i = 0; i < len; i += 2) {
251
+ data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
252
+ }
253
+ return data;
254
+ }
255
+
256
+ public static String decryptChecksum(String checksum, String publicKey) throws IOException {
257
+ if (publicKey.isEmpty()) {
258
+ logger.error("No encryption set (public key) ignored");
259
+ return checksum;
260
+ }
261
+ try {
262
+ // TODO: remove this in a month or two
263
+ // Determine if input is hex or base64 encoded
264
+ // Hex strings only contain 0-9 and a-f, while base64 contains other characters
265
+ byte[] checksumBytes;
266
+ String detectedFormat;
267
+ if (checksum.matches("^[0-9a-fA-F]+$")) {
268
+ // Hex encoded (new format from CLI for plugin versions >= 5.30.0, 6.30.0, 7.30.0)
269
+ checksumBytes = hexStringToByteArray(checksum);
270
+ detectedFormat = "hex";
271
+ } else {
272
+ // TODO: remove backwards compatibility
273
+ // Base64 encoded (old format for backwards compatibility)
274
+ checksumBytes = Base64.decode(checksum, Base64.DEFAULT);
275
+ detectedFormat = "base64";
276
+ }
277
+ logger.debug(
278
+ "Received checksum format: " +
279
+ detectedFormat +
280
+ " (length: " +
281
+ checksum.length() +
282
+ " chars, " +
283
+ checksumBytes.length +
284
+ " bytes)"
285
+ );
286
+
287
+ // RSA-2048 encrypted data must be exactly 256 bytes
288
+ // If the checksum is not 256 bytes, the bundle was not encrypted properly
289
+ if (checksumBytes.length != 256) {
290
+ logger.error(
291
+ "Checksum is not RSA encrypted (size: " +
292
+ checksumBytes.length +
293
+ " bytes, expected 256 for RSA-2048). Bundle must be uploaded with encryption when public key is configured."
294
+ );
295
+ throw new IOException("Bundle checksum is not encrypted. Upload bundle with --key flag when encryption is configured.");
296
+ }
297
+
298
+ PublicKey pKey = CryptoCipher.stringToPublicKey(publicKey);
299
+ byte[] decryptedChecksum = CryptoCipher.decryptRSA(checksumBytes, pKey);
300
+ // Return as hex string to match calcChecksum output format
301
+ StringBuilder hexString = new StringBuilder();
302
+ for (byte b : decryptedChecksum) {
303
+ String hex = Integer.toHexString(0xff & b);
304
+ if (hex.length() == 1) hexString.append('0');
305
+ hexString.append(hex);
306
+ }
307
+ String result = hexString.toString();
308
+
309
+ // Detect checksum algorithm based on length
310
+ String detectedAlgorithm;
311
+ if (decryptedChecksum.length == 32) {
312
+ detectedAlgorithm = "SHA-256";
313
+ } else if (decryptedChecksum.length == 4) {
314
+ detectedAlgorithm = "CRC32 (deprecated)";
315
+ logger.error("CRC32 checksum detected - deprecated algorithm");
316
+ } else {
317
+ detectedAlgorithm = "unknown (" + decryptedChecksum.length + " bytes)";
318
+ logger.error("Unknown checksum algorithm detected");
319
+ logger.debug("Byte count: " + decryptedChecksum.length + ", Expected: 32 (SHA-256)");
320
+ }
321
+ logger.debug(
322
+ "Decrypted checksum: " +
323
+ detectedAlgorithm +
324
+ " hex format (length: " +
325
+ result.length() +
326
+ " chars, " +
327
+ decryptedChecksum.length +
328
+ " bytes)"
329
+ );
330
+ return result;
331
+ } catch (GeneralSecurityException e) {
332
+ logger.error("Checksum decryption failed");
333
+ logger.debug("Error: " + e.getMessage());
334
+ throw new IOException("Decryption failed: " + e.getMessage());
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Detect checksum algorithm based on hex string length.
340
+ * SHA-256 = 64 hex chars (32 bytes)
341
+ * CRC32 = 8 hex chars (4 bytes)
342
+ */
343
+ public static String detectChecksumAlgorithm(String hexChecksum) {
344
+ if (hexChecksum == null || hexChecksum.isEmpty()) {
345
+ return "empty";
346
+ }
347
+ int len = hexChecksum.length();
348
+ if (len == 64) {
349
+ return "SHA-256";
350
+ } else if (len == 8) {
351
+ return "CRC32 (deprecated)";
352
+ } else {
353
+ return "unknown (" + len + " hex chars)";
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Log checksum info and warn if deprecated algorithm detected.
359
+ */
360
+ public static void logChecksumInfo(String label, String hexChecksum) {
361
+ String algorithm = detectChecksumAlgorithm(hexChecksum);
362
+ logger.debug(label + ": " + algorithm + " hex format (length: " + hexChecksum.length() + " chars)");
363
+ if (algorithm.contains("CRC32")) {
364
+ logger.error("CRC32 checksum detected - deprecated algorithm");
365
+ } else if (algorithm.contains("unknown")) {
366
+ logger.error("Unknown checksum algorithm detected");
367
+ logger.debug("Char count: " + hexChecksum.length() + ", Expected: 64 (SHA-256)");
368
+ }
369
+ }
370
+
371
+ // 256 KiB: one size for checksum, copy, and decode.
372
+ // 64 workers * 256 KiB = 16 MiB for one buffer; AES/Brotli hold two (~32 MiB).
373
+ static final int IO_BUFFER_BYTES = 256 * 1024;
374
+
375
+ static int ioBufferBytes() {
376
+ return IO_BUFFER_BYTES;
377
+ }
378
+
379
+ static int checksumBufferBytes() {
380
+ return IO_BUFFER_BYTES;
381
+ }
382
+
383
+ static int copyBufferBytes() {
384
+ return IO_BUFFER_BYTES;
385
+ }
386
+
387
+ public static String calcChecksum(File file) {
388
+ try (FileInputStream fis = new FileInputStream(file)) {
389
+ return calcChecksum(fis);
390
+ } catch (IOException e) {
391
+ logger.error("Cannot calculate checksum");
392
+ logger.debug("Path: " + file.getPath() + ", Error: " + e.getMessage());
393
+ return "";
394
+ }
395
+ }
396
+
397
+ public static String calcChecksum(InputStream inputStream) {
398
+ final int BUFFER_SIZE = checksumBufferBytes();
399
+ MessageDigest digest;
400
+ try {
401
+ digest = MessageDigest.getInstance("SHA-256");
402
+ } catch (java.security.NoSuchAlgorithmException e) {
403
+ logger.error("SHA-256 algorithm not available");
404
+ return "";
405
+ }
406
+
407
+ try {
408
+ byte[] buffer = new byte[BUFFER_SIZE];
409
+ int length;
410
+ while ((length = inputStream.read(buffer)) != -1) {
411
+ digest.update(buffer, 0, length);
412
+ }
413
+ return digestToHex(digest);
414
+ } catch (IOException e) {
415
+ logger.error("Cannot calculate checksum");
416
+ logger.debug("Error: " + e.getMessage());
417
+ return "";
418
+ }
419
+ }
420
+
421
+ static String digestToHex(MessageDigest digest) {
422
+ byte[] hash = digest.digest();
423
+ StringBuilder hexString = new StringBuilder(hash.length * 2);
424
+ for (byte b : hash) {
425
+ String hex = Integer.toHexString(0xff & b);
426
+ if (hex.length() == 1) hexString.append('0');
427
+ hexString.append(hex);
428
+ }
429
+ return hexString.toString();
430
+ }
431
+
432
+ static String shortPathKey(String fileName) {
433
+ try {
434
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
435
+ digest.update((fileName == null ? "" : fileName).getBytes(java.nio.charset.StandardCharsets.UTF_8));
436
+ return digestToHex(digest).substring(0, 16);
437
+ } catch (java.security.NoSuchAlgorithmException e) {
438
+ return Integer.toHexString((fileName == null ? "" : fileName).hashCode());
439
+ }
440
+ }
441
+
442
+ private static byte[] createDEREncoding(int tag, byte[] value) {
443
+ if (tag < 0 || tag >= 0xFF) {
444
+ throw new IllegalArgumentException("Currently only single byte tags supported");
445
+ }
446
+
447
+ byte[] lengthEncoding = createDERLengthEncoding(value.length);
448
+
449
+ int size = 1 + lengthEncoding.length + value.length;
450
+ byte[] derEncodingBuf = new byte[size];
451
+
452
+ int off = 0;
453
+ derEncodingBuf[off++] = (byte) tag;
454
+ System.arraycopy(lengthEncoding, 0, derEncodingBuf, off, lengthEncoding.length);
455
+ off += lengthEncoding.length;
456
+ System.arraycopy(value, 0, derEncodingBuf, off, value.length);
457
+
458
+ return derEncodingBuf;
459
+ }
460
+
461
+ private static byte[] createDERLengthEncoding(int size) {
462
+ if (size <= 0x7F) {
463
+ // single byte length encoding
464
+ return new byte[] { (byte) size };
465
+ } else if (size <= 0xFF) {
466
+ // double byte length encoding
467
+ return new byte[] { (byte) 0x81, (byte) size };
468
+ } else if (size <= 0xFFFF) {
469
+ // triple byte length encoding
470
+ return new byte[] { (byte) 0x82, (byte) (size >> Byte.SIZE), (byte) size };
471
+ }
472
+
473
+ throw new IllegalArgumentException("size too large, only up to 64KiB length encoding supported: " + size);
474
+ }
475
+
476
+ /**
477
+ * Get first 20 characters of the public key for identification.
478
+ * Returns 20-character string or empty string if key is invalid/empty.
479
+ * The first 12 chars are always "MIIBCgKCAQEA" for RSA 2048-bit keys,
480
+ * so the unique part starts at character 13.
481
+ */
482
+ public static String calcKeyId(String publicKey) {
483
+ if (publicKey == null || publicKey.isEmpty()) {
484
+ return "";
485
+ }
486
+
487
+ // Remove PEM headers and whitespace to get the raw key data
488
+ String cleanedKey = publicKey
489
+ .replaceAll("\\s+", "")
490
+ .replace("-----BEGINRSAPUBLICKEY-----", "")
491
+ .replace("-----ENDRSAPUBLICKEY-----", "");
492
+
493
+ // Return first 20 characters of the base64-encoded key
494
+ return cleanedKey.length() >= 20 ? cleanedKey.substring(0, 20) : cleanedKey;
495
+ }
496
+ }
@@ -0,0 +1,44 @@
1
+ package ee.forgr.capacitor_updater;
2
+
3
+ import java.util.HashMap;
4
+ import java.util.Map;
5
+ import org.json.JSONArray;
6
+
7
+ public class DataManager {
8
+
9
+ private static DataManager instance;
10
+ private final Map<String, JSONArray> manifestsById = new HashMap<>();
11
+
12
+ private DataManager() {}
13
+
14
+ public static synchronized DataManager getInstance() {
15
+ if (instance == null) {
16
+ instance = new DataManager();
17
+ }
18
+ return instance;
19
+ }
20
+
21
+ public synchronized void setManifest(String downloadId, JSONArray manifest) {
22
+ if (downloadId == null || manifest == null) {
23
+ return;
24
+ }
25
+ this.manifestsById.put(downloadId, manifest);
26
+ }
27
+
28
+ public synchronized JSONArray getAndClearManifest(String downloadId) {
29
+ if (downloadId == null) {
30
+ return null;
31
+ }
32
+ return this.manifestsById.remove(downloadId);
33
+ }
34
+
35
+ public synchronized void clearManifest(String downloadId) {
36
+ if (downloadId != null) {
37
+ this.manifestsById.remove(downloadId);
38
+ }
39
+ }
40
+
41
+ public synchronized void clearAllManifests() {
42
+ this.manifestsById.clear();
43
+ }
44
+ }
@@ -0,0 +1,56 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ import androidx.annotation.NonNull;
10
+ import java.util.Objects;
11
+
12
+ public class DelayCondition {
13
+
14
+ private DelayUntilNext kind;
15
+
16
+ private String value;
17
+
18
+ public DelayCondition(DelayUntilNext kind, String value) {
19
+ this.kind = kind;
20
+ this.value = value;
21
+ }
22
+
23
+ public DelayUntilNext getKind() {
24
+ return kind;
25
+ }
26
+
27
+ public void setKind(DelayUntilNext kind) {
28
+ this.kind = kind;
29
+ }
30
+
31
+ public String getValue() {
32
+ return value;
33
+ }
34
+
35
+ public void setValue(String value) {
36
+ this.value = value;
37
+ }
38
+
39
+ @Override
40
+ public boolean equals(Object o) {
41
+ if (this == o) return true;
42
+ if (!(o instanceof DelayCondition that)) return false;
43
+ return getKind() == that.getKind() && Objects.equals(getValue(), that.getValue());
44
+ }
45
+
46
+ @Override
47
+ public int hashCode() {
48
+ return Objects.hash(getKind(), getValue());
49
+ }
50
+
51
+ @NonNull
52
+ @Override
53
+ public String toString() {
54
+ return "DelayCondition{" + "kind=" + kind + ", value='" + value + '\'' + '}';
55
+ }
56
+ }
@@ -0,0 +1,14 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ public enum DelayUntilNext {
10
+ background,
11
+ kill,
12
+ nativeVersion,
13
+ date
14
+ }