@capgo/capacitor-updater 9.0.0 → 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2607 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -12,142 +12,585 @@ package ee.forgr.capacitor_updater;
12
12
  * references: http://stackoverflow.com/questions/12471999/rsa-encryption-decryption-in-android
13
13
  */
14
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;
15
20
  import java.security.GeneralSecurityException;
16
21
  import java.security.InvalidAlgorithmParameterException;
17
22
  import java.security.InvalidKeyException;
18
23
  import java.security.KeyFactory;
24
+ import java.security.MessageDigest;
19
25
  import java.security.NoSuchAlgorithmException;
20
- import java.security.PrivateKey;
26
+ import java.security.PublicKey;
21
27
  import java.security.spec.InvalidKeySpecException;
22
- import java.security.spec.MGF1ParameterSpec;
23
- import java.security.spec.PKCS8EncodedKeySpec;
28
+ import java.security.spec.X509EncodedKeySpec;
24
29
  import javax.crypto.BadPaddingException;
25
30
  import javax.crypto.Cipher;
26
31
  import javax.crypto.IllegalBlockSizeException;
27
32
  import javax.crypto.NoSuchPaddingException;
28
33
  import javax.crypto.SecretKey;
29
34
  import javax.crypto.spec.IvParameterSpec;
30
- import javax.crypto.spec.OAEPParameterSpec;
31
- import javax.crypto.spec.PSource;
32
35
  import javax.crypto.spec.SecretKeySpec;
33
36
 
34
37
  public class CryptoCipher {
35
38
 
36
- public static byte[] decryptRSA(byte[] source, PrivateKey privateKey)
37
- throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
38
- Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
39
- OAEPParameterSpec oaepParams = new OAEPParameterSpec(
40
- "SHA-256",
41
- "MGF1",
42
- new MGF1ParameterSpec("SHA-256"),
43
- PSource.PSpecified.DEFAULT
44
- );
45
- cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParams);
46
- byte[] decryptedBytes = cipher.doFinal(source);
47
- return decryptedBytes;
48
- }
49
-
50
- public static byte[] decryptAES(byte[] cipherText, SecretKey key, byte[] iv) {
51
- try {
52
- IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
53
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
54
- SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
55
- cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
56
- byte[] decryptedText = cipher.doFinal(cipherText);
57
- return decryptedText;
58
- } catch (Exception e) {
59
- e.printStackTrace();
60
- }
61
- return null;
62
- }
63
-
64
- public static SecretKey byteToSessionKey(byte[] sessionKey) {
65
- // rebuild key using SecretKeySpec
66
- SecretKey originalKey = new SecretKeySpec(
67
- sessionKey,
68
- 0,
69
- sessionKey.length,
70
- "AES"
71
- );
72
- return originalKey;
73
- }
74
-
75
- private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes)
76
- throws GeneralSecurityException {
77
- KeyFactory keyFactory = KeyFactory.getInstance("RSA");
78
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
79
- try {
80
- return keyFactory.generatePrivate(keySpec);
81
- } catch (InvalidKeySpecException e) {
82
- throw new IllegalArgumentException("Unexpected key format!", e);
83
- }
84
- }
85
-
86
- private static byte[] join(byte[] byteArray1, byte[] byteArray2) {
87
- byte[] bytes = new byte[byteArray1.length + byteArray2.length];
88
- System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
89
- System.arraycopy(
90
- byteArray2,
91
- 0,
92
- bytes,
93
- byteArray1.length,
94
- byteArray2.length
95
- );
96
- return bytes;
97
- }
98
-
99
- private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes)
100
- throws GeneralSecurityException {
101
- // We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
102
- int pkcs1Length = pkcs1Bytes.length;
103
- int totalLength = pkcs1Length + 22;
104
- byte[] pkcs8Header = new byte[] {
105
- 0x30,
106
- (byte) 0x82,
107
- (byte) ((totalLength >> 8) & 0xff),
108
- (byte) (totalLength & 0xff), // Sequence + total length
109
- 0x2,
110
- 0x1,
111
- 0x0, // Integer (0)
112
- 0x30,
113
- 0xD,
114
- 0x6,
115
- 0x9,
116
- 0x2A,
117
- (byte) 0x86,
118
- 0x48,
119
- (byte) 0x86,
120
- (byte) 0xF7,
121
- 0xD,
122
- 0x1,
123
- 0x1,
124
- 0x1,
125
- 0x5,
126
- 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
127
- 0x4,
128
- (byte) 0x82,
129
- (byte) ((pkcs1Length >> 8) & 0xff),
130
- (byte) (pkcs1Length & 0xff), // Octet string + length
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
131
111
  };
132
- byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
133
- return readPkcs8PrivateKey(pkcs8bytes);
134
- }
135
-
136
- public static PrivateKey stringToPrivateKey(String private_key)
137
- throws GeneralSecurityException {
138
- // Base64 decode the result
139
-
140
- String pkcs1Pem = private_key.toString();
141
- pkcs1Pem = pkcs1Pem.replace("-----BEGIN RSA PRIVATE KEY-----", "");
142
- pkcs1Pem = pkcs1Pem.replace("-----END RSA PRIVATE KEY-----", "");
143
- pkcs1Pem = pkcs1Pem.replace("\\n", "");
144
- pkcs1Pem = pkcs1Pem.replace(" ", "");
145
-
146
- byte[] pkcs1EncodedBytes = Base64.decode(
147
- pkcs1Pem.getBytes(),
148
- Base64.DEFAULT
149
- );
150
- // extract the private key
151
- return readPkcs1PrivateKey(pkcs1EncodedBytes);
152
- }
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
+ /**
147
+ * Decrypts {@code file} in place. {@code expectedCiphertextSha256} is the SHA-256 of the encrypted bytes taken from
148
+ * the signed checksum ({@link BundleChecksum#ciphertext}): the file is hashed and rejected before any AES work when
149
+ * it does not match, so tampered ciphertext never reaches the cipher.
150
+ */
151
+ public static void decryptFile(
152
+ final File file,
153
+ final String publicKey,
154
+ final String ivSessionKey,
155
+ final String expectedCiphertextSha256
156
+ ) throws IOException {
157
+ if (publicKey.isEmpty() || !isValidSessionKey(ivSessionKey)) {
158
+ if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
159
+ return;
160
+ }
161
+ new DecryptionSession(publicKey, ivSessionKey).decryptFile(file, expectedCiphertextSha256);
162
+ }
163
+
164
+ static final String CIPHERTEXT_CHECKSUM_MISMATCH = "Checksum verification failed: encrypted bytes do not match the signed checksum";
165
+
166
+ /** Rejects {@code file} unless its SHA-256 equals the signed ciphertext checksum. Runs before decryption. */
167
+ static void verifyCiphertextChecksum(final File file, final String expectedCiphertextSha256) throws IOException {
168
+ if (!isSha256Hex(expectedCiphertextSha256)) {
169
+ throw new IOException("Encrypted bundle has no signed ciphertext checksum. Re-upload the bundle with a current Capgo CLI.");
170
+ }
171
+ final String actual = calcChecksumOrThrow(file);
172
+ if (!expectedCiphertextSha256.equalsIgnoreCase(actual)) {
173
+ if (logger != null) {
174
+ logger.error("Encrypted file checksum mismatch, refusing to decrypt");
175
+ logger.debug("Expected: " + expectedCiphertextSha256 + ", Got: " + actual);
176
+ }
177
+ throw new IOException(CIPHERTEXT_CHECKSUM_MISMATCH);
178
+ }
179
+ }
180
+
181
+ static boolean isSha256Hex(final String value) {
182
+ return value != null && value.length() == 64 && value.matches("^[0-9a-fA-F]+$");
183
+ }
184
+
185
+ // A manifest shares key setup, while each file still creates its own CBC cipher.
186
+ static final class DecryptionSession {
187
+
188
+ private final String publicKey;
189
+ private final String ivSessionKey;
190
+ private PreparedKey prepared;
191
+ private IOException failure;
192
+
193
+ DecryptionSession(String publicKey, String ivSessionKey) {
194
+ this.publicKey = publicKey;
195
+ this.ivSessionKey = ivSessionKey;
196
+ }
197
+
198
+ private synchronized PreparedKey key() throws IOException {
199
+ if (failure != null) throw new IOException(failure.getMessage(), failure);
200
+ if (prepared == null) {
201
+ try {
202
+ prepared = prepareDecryptionKey(publicKey, ivSessionKey);
203
+ } catch (IOException error) {
204
+ failure = error;
205
+ throw error;
206
+ } catch (RuntimeException error) {
207
+ // Malformed Base64 throws IllegalArgumentException: cache it like any other bad key.
208
+ failure = new IOException("AES file decryption failed: invalid session key", error);
209
+ throw failure;
210
+ }
211
+ }
212
+ return prepared;
213
+ }
214
+
215
+ boolean isEncrypted() {
216
+ return publicKey != null && !publicKey.isEmpty();
217
+ }
218
+
219
+ void decryptFile(File file, String expectedCiphertextSha256) throws IOException {
220
+ if (!isEncrypted()) {
221
+ if (logger != null) logger.info("Encryption not set, no public key or session, ignored");
222
+ return;
223
+ }
224
+ // Authenticate the encrypted bytes first: CBC padding is only ever checked on signed ciphertext.
225
+ verifyCiphertextChecksum(file, expectedCiphertextSha256);
226
+ PreparedKey key = key();
227
+ decryptAesFile(file, key.key, key.iv);
228
+ }
229
+ }
230
+
231
+ private static final class PreparedKey {
232
+
233
+ final SecretKey key;
234
+ final byte[] iv;
235
+
236
+ PreparedKey(SecretKey key, byte[] iv) {
237
+ this.key = key;
238
+ this.iv = iv;
239
+ }
240
+ }
241
+
242
+ private static PreparedKey prepareDecryptionKey(String publicKey, String ivSessionKey) throws IOException {
243
+ if (!isValidSessionKey(ivSessionKey)) throw new IOException("AES file decryption failed: session key is required");
244
+ // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
245
+ if (!publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
246
+ if (logger != null) {
247
+ logger.error("The public key is not a valid RSA Public key");
248
+ }
249
+ throw new IOException("AES file decryption failed: the public key is not a valid RSA public key");
250
+ }
251
+
252
+ try {
253
+ String ivB64 = ivSessionKey.split(":")[0];
254
+ String sessionKeyB64 = ivSessionKey.split(":")[1];
255
+ byte[] iv = Base64.decode(ivB64.getBytes(), Base64.DEFAULT);
256
+ byte[] sessionKey = Base64.decode(sessionKeyB64.getBytes(), Base64.DEFAULT);
257
+ if (iv.length != 16) {
258
+ throw new IOException("AES file decryption failed: IV must be 16 bytes");
259
+ }
260
+ PublicKey pKey = CryptoCipher.stringToPublicKey(publicKey);
261
+ byte[] decryptedSessionKey = CryptoCipher.decryptRSA(sessionKey, pKey);
262
+ if (decryptedSessionKey == null || decryptedSessionKey.length != 16) {
263
+ throw new IOException("AES file decryption failed: decrypted session key must be 16 bytes");
264
+ }
265
+
266
+ SecretKey sKey = CryptoCipher.byteToSessionKey(decryptedSessionKey);
267
+ return new PreparedKey(sKey, iv);
268
+ } catch (GeneralSecurityException e) {
269
+ if (logger != null) {
270
+ logger.info("decryptFile fail");
271
+ }
272
+ throw new IOException("AES file decryption failed: " + e.getMessage(), e);
273
+ }
274
+ }
275
+
276
+ static void decryptAesFile(File file, SecretKey key, byte[] iv) throws IOException {
277
+ if (key == null) {
278
+ throw new IOException("AES file decryption failed: missing session key");
279
+ }
280
+ if (iv == null) {
281
+ throw new IOException("AES file decryption failed: missing IV");
282
+ }
283
+ if (iv.length != 16) {
284
+ throw new IOException("AES file decryption failed: IV must be 16 bytes");
285
+ }
286
+ byte[] keyBytes = key.getEncoded();
287
+ if (keyBytes == null || keyBytes.length != 16) {
288
+ throw new IOException("AES file decryption failed: session key must be 16 bytes");
289
+ }
290
+ if (file.length() == 0) {
291
+ throw new IOException("Empty encrypted data");
292
+ }
293
+ File parent = file.getAbsoluteFile().getParentFile();
294
+ if (parent == null) {
295
+ throw new IOException("Cannot create temp file for " + file.getAbsolutePath());
296
+ }
297
+ File tempFile = File.createTempFile("capgo-aes-", ".tmp", parent);
298
+ try {
299
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
300
+ cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(iv));
301
+ byte[] inBuf = new byte[ioBufferBytes()];
302
+ // Reuse one output buffer. cipher.update(in) allocates a new byte[] per chunk.
303
+ byte[] outBuf = new byte[inBuf.length + 16];
304
+ try (FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(tempFile)) {
305
+ int n;
306
+ while ((n = fis.read(inBuf)) != -1) {
307
+ int outLen = cipher.update(inBuf, 0, n, outBuf, 0);
308
+ if (outLen > 0) {
309
+ fos.write(outBuf, 0, outLen);
310
+ }
311
+ }
312
+ int last = cipher.doFinal(outBuf, 0);
313
+ if (last > 0) {
314
+ fos.write(outBuf, 0, last);
315
+ }
316
+ }
317
+ if (tempFile.length() == 0) {
318
+ throw new IOException("Empty decrypted data");
319
+ }
320
+ replaceFile(tempFile, file);
321
+ tempFile = null;
322
+ } catch (GeneralSecurityException e) {
323
+ throw new IOException("AES file decryption failed: " + e.getMessage(), e);
324
+ } finally {
325
+ if (tempFile != null && tempFile.exists()) {
326
+ tempFile.delete();
327
+ }
328
+ }
329
+ }
330
+
331
+ static void replaceFile(File from, File to) throws IOException {
332
+ if (from.renameTo(to)) {
333
+ return;
334
+ }
335
+ throw new IOException("Failed to replace file: " + to.getAbsolutePath());
336
+ }
337
+
338
+ private static byte[] hexStringToByteArray(String s) {
339
+ int len = s.length();
340
+ byte[] data = new byte[len / 2];
341
+ for (int i = 0; i < len; i += 2) {
342
+ data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
343
+ }
344
+ return data;
345
+ }
346
+
347
+ /** Plaintext and ciphertext SHA-256 digests recovered from a signed bundle checksum, as lowercase hex. */
348
+ public static final class BundleChecksum {
349
+
350
+ /** SHA-256 of the decrypted bundle or file, the value compared after decryption. */
351
+ public final String plain;
352
+ /** SHA-256 of the encrypted bytes as served, checked before decryption. {@code null} without a public key. */
353
+ public final String ciphertext;
354
+
355
+ BundleChecksum(final String plain, final String ciphertext) {
356
+ this.plain = plain;
357
+ this.ciphertext = ciphertext;
358
+ }
359
+ }
360
+
361
+ /** Size of the signed checksum payload: SHA-256 of the plaintext followed by SHA-256 of the ciphertext. */
362
+ static final int SIGNED_CHECKSUM_PAYLOAD_BYTES = 64;
363
+
364
+ /**
365
+ * Decrypts the RSA encrypted bundle checksum. Since 9.0.0 the signed payload is 64 bytes: the SHA-256 of the
366
+ * plaintext followed by the SHA-256 of the encrypted bytes (Capgo CLI "V4" checksum). Returns {@code checksum}
367
+ * as the plain digest when no public key is configured. Throws for anything that is not an even-length hex
368
+ * string of 256 bytes signed with the matching private key, and for the 32-byte payload of older CLIs.
369
+ */
370
+ public static BundleChecksum decryptBundleChecksum(String checksum, String publicKey) throws IOException {
371
+ if (publicKey.isEmpty()) {
372
+ logger.error("No encryption set (public key) ignored");
373
+ return new BundleChecksum(checksum, null);
374
+ }
375
+ try {
376
+ // The encrypted checksum is hex encoded. The base64 format of CLI uploads made for plugin
377
+ // versions older than 5.30.0 / 6.30.0 / 7.30.0 is no longer accepted since 9.0.0.
378
+ // An odd length is rejected too: hexStringToByteArray would read past the last digit.
379
+ if (checksum.length() % 2 != 0 || !checksum.matches("^[0-9a-fA-F]+$")) {
380
+ logger.error("Cannot decode checksum as hex. Re-upload the bundle with a current Capgo CLI.");
381
+ throw new IOException("Bundle checksum is not hex encoded. Re-upload the bundle with a current Capgo CLI.");
382
+ }
383
+ final byte[] checksumBytes = hexStringToByteArray(checksum);
384
+ logger.debug("Received checksum format: hex (length: " + checksum.length() + " chars, " + checksumBytes.length + " bytes)");
385
+
386
+ // RSA-2048 encrypted data must be exactly 256 bytes
387
+ // If the checksum is not 256 bytes, the bundle was not encrypted properly
388
+ if (checksumBytes.length != 256) {
389
+ logger.error(
390
+ "Checksum is not RSA encrypted (size: " +
391
+ checksumBytes.length +
392
+ " bytes, expected 256 for RSA-2048). Bundle must be uploaded with encryption when public key is configured."
393
+ );
394
+ throw new IOException("Bundle checksum is not encrypted. Upload bundle with --key flag when encryption is configured.");
395
+ }
396
+
397
+ PublicKey pKey = CryptoCipher.stringToPublicKey(publicKey);
398
+ byte[] decryptedChecksum = CryptoCipher.decryptRSA(checksumBytes, pKey);
399
+ if (decryptedChecksum == null || decryptedChecksum.length != SIGNED_CHECKSUM_PAYLOAD_BYTES) {
400
+ int size = decryptedChecksum == null ? 0 : decryptedChecksum.length;
401
+ logger.error("Signed checksum has no ciphertext digest. Re-upload the bundle with a Capgo CLI that supports updater 9.");
402
+ logger.debug("Decrypted checksum bytes: " + size + ", expected: " + SIGNED_CHECKSUM_PAYLOAD_BYTES);
403
+ throw new IOException(
404
+ "Bundle checksum has no signed ciphertext digest (" +
405
+ size +
406
+ " bytes). Re-upload the bundle with a Capgo CLI that supports updater 9."
407
+ );
408
+ }
409
+ final String hex = bytesToHex(decryptedChecksum);
410
+ final BundleChecksum result = new BundleChecksum(hex.substring(0, 64), hex.substring(64));
411
+ logger.debug("Decrypted checksum: SHA-256 of plaintext and ciphertext (64 bytes)");
412
+ return result;
413
+ } catch (GeneralSecurityException e) {
414
+ logger.error("Checksum decryption failed");
415
+ logger.debug("Error: " + e.getMessage());
416
+ throw new IOException("Decryption failed: " + e.getMessage());
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Returns the SHA-256 of the plaintext from the signed bundle checksum, or {@code checksum} unchanged when no
422
+ * public key is configured. See {@link #decryptBundleChecksum(String, String)}.
423
+ */
424
+ public static String decryptChecksum(String checksum, String publicKey) throws IOException {
425
+ return decryptBundleChecksum(checksum, publicKey).plain;
426
+ }
427
+
428
+ private static String bytesToHex(final byte[] bytes) {
429
+ StringBuilder hexString = new StringBuilder(bytes.length * 2);
430
+ for (byte b : bytes) {
431
+ String hex = Integer.toHexString(0xff & b);
432
+ if (hex.length() == 1) hexString.append('0');
433
+ hexString.append(hex);
434
+ }
435
+ return hexString.toString();
436
+ }
437
+
438
+ /**
439
+ * Detect checksum algorithm based on hex string length.
440
+ * SHA-256 = 64 hex chars (32 bytes). It is the only supported algorithm.
441
+ */
442
+ public static String detectChecksumAlgorithm(String hexChecksum) {
443
+ if (hexChecksum == null || hexChecksum.isEmpty()) {
444
+ return "empty";
445
+ }
446
+ int len = hexChecksum.length();
447
+ if (len == 64) {
448
+ return "SHA-256";
449
+ } else {
450
+ return "unknown (" + len + " hex chars)";
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Log checksum info and warn if the checksum is not SHA-256.
456
+ */
457
+ public static void logChecksumInfo(String label, String hexChecksum) {
458
+ String algorithm = detectChecksumAlgorithm(hexChecksum);
459
+ logger.debug(label + ": " + algorithm + " hex format (length: " + hexChecksum.length() + " chars)");
460
+ if (algorithm.contains("unknown")) {
461
+ logger.error("Unknown checksum algorithm detected");
462
+ logger.debug("Char count: " + hexChecksum.length() + ", Expected: 64 (SHA-256)");
463
+ }
464
+ }
465
+
466
+ // 256 KiB: one size for checksum, copy, and decode.
467
+ // 64 workers * 256 KiB = 16 MiB for one buffer; AES/Brotli hold two (~32 MiB).
468
+ static final int IO_BUFFER_BYTES = 256 * 1024;
469
+
470
+ static int ioBufferBytes() {
471
+ return IO_BUFFER_BYTES;
472
+ }
473
+
474
+ static int checksumBufferBytes() {
475
+ return IO_BUFFER_BYTES;
476
+ }
477
+
478
+ static int copyBufferBytes() {
479
+ return IO_BUFFER_BYTES;
480
+ }
481
+
482
+ public static String calcChecksum(File file) {
483
+ try (FileInputStream fis = new FileInputStream(file)) {
484
+ return calcChecksum(fis);
485
+ } catch (IOException e) {
486
+ logger.error("Cannot calculate checksum");
487
+ logger.debug("Path: " + file.getPath() + ", Error: " + e.getMessage());
488
+ return "";
489
+ }
490
+ }
491
+
492
+ public static String calcChecksum(InputStream inputStream) {
493
+ try {
494
+ return calcChecksumOrThrow(inputStream);
495
+ } catch (IOException error) {
496
+ logger.error("Cannot calculate checksum");
497
+ logger.debug("Error: " + error.getMessage());
498
+ return "";
499
+ }
500
+ }
501
+
502
+ static String calcChecksumOrThrow(File file) throws IOException {
503
+ try (FileInputStream input = new FileInputStream(file)) {
504
+ return calcChecksumOrThrow(input);
505
+ }
506
+ }
507
+
508
+ static String calcChecksumOrThrow(InputStream input) throws IOException {
509
+ final MessageDigest digest;
510
+ try {
511
+ digest = MessageDigest.getInstance("SHA-256");
512
+ } catch (java.security.NoSuchAlgorithmException error) {
513
+ throw new IOException("SHA-256 algorithm not available", error);
514
+ }
515
+ byte[] buffer = new byte[checksumBufferBytes()];
516
+ int length;
517
+ while ((length = input.read(buffer)) != -1) digest.update(buffer, 0, length);
518
+ return digestToHex(digest);
519
+ }
520
+
521
+ static String digestToHex(MessageDigest digest) {
522
+ byte[] hash = digest.digest();
523
+ StringBuilder hexString = new StringBuilder(hash.length * 2);
524
+ for (byte b : hash) {
525
+ String hex = Integer.toHexString(0xff & b);
526
+ if (hex.length() == 1) hexString.append('0');
527
+ hexString.append(hex);
528
+ }
529
+ return hexString.toString();
530
+ }
531
+
532
+ static String shortPathKey(String fileName) {
533
+ try {
534
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
535
+ digest.update((fileName == null ? "" : fileName).getBytes(java.nio.charset.StandardCharsets.UTF_8));
536
+ return digestToHex(digest).substring(0, 16);
537
+ } catch (java.security.NoSuchAlgorithmException e) {
538
+ return Integer.toHexString((fileName == null ? "" : fileName).hashCode());
539
+ }
540
+ }
541
+
542
+ private static byte[] createDEREncoding(int tag, byte[] value) {
543
+ if (tag < 0 || tag >= 0xFF) {
544
+ throw new IllegalArgumentException("Currently only single byte tags supported");
545
+ }
546
+
547
+ byte[] lengthEncoding = createDERLengthEncoding(value.length);
548
+
549
+ int size = 1 + lengthEncoding.length + value.length;
550
+ byte[] derEncodingBuf = new byte[size];
551
+
552
+ int off = 0;
553
+ derEncodingBuf[off++] = (byte) tag;
554
+ System.arraycopy(lengthEncoding, 0, derEncodingBuf, off, lengthEncoding.length);
555
+ off += lengthEncoding.length;
556
+ System.arraycopy(value, 0, derEncodingBuf, off, value.length);
557
+
558
+ return derEncodingBuf;
559
+ }
560
+
561
+ private static byte[] createDERLengthEncoding(int size) {
562
+ if (size <= 0x7F) {
563
+ // single byte length encoding
564
+ return new byte[] { (byte) size };
565
+ } else if (size <= 0xFF) {
566
+ // double byte length encoding
567
+ return new byte[] { (byte) 0x81, (byte) size };
568
+ } else if (size <= 0xFFFF) {
569
+ // triple byte length encoding
570
+ return new byte[] { (byte) 0x82, (byte) (size >> Byte.SIZE), (byte) size };
571
+ }
572
+
573
+ throw new IllegalArgumentException("size too large, only up to 64KiB length encoding supported: " + size);
574
+ }
575
+
576
+ /**
577
+ * Get first 20 characters of the public key for identification.
578
+ * Returns 20-character string or empty string if key is invalid/empty.
579
+ * The first 12 chars are always "MIIBCgKCAQEA" for RSA 2048-bit keys,
580
+ * so the unique part starts at character 13.
581
+ */
582
+ public static String calcKeyId(String publicKey) {
583
+ if (publicKey == null || publicKey.isEmpty()) {
584
+ return "";
585
+ }
586
+
587
+ // Remove PEM headers and whitespace to get the raw key data
588
+ String cleanedKey = publicKey
589
+ .replaceAll("\\s+", "")
590
+ .replace("-----BEGINRSAPUBLICKEY-----", "")
591
+ .replace("-----ENDRSAPUBLICKEY-----", "");
592
+
593
+ // Return first 20 characters of the base64-encoded key
594
+ return cleanedKey.length() >= 20 ? cleanedKey.substring(0, 20) : cleanedKey;
595
+ }
153
596
  }