native-update 3.4.2 → 4.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 (46) hide show
  1. package/AI-INTEGRATION-GUIDE.md +26 -16
  2. package/NativeUpdate.podspec +2 -2
  3. package/README.md +24 -20
  4. package/android/build.gradle +37 -33
  5. package/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  6. package/android/proguard-rules.pro +0 -3
  7. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +45 -49
  8. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +12 -10
  9. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +12 -21
  10. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +3 -34
  11. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +206 -72
  12. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +74 -37
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +169 -179
  14. package/android/variables.gradle +2 -2
  15. package/cli/commands/bundle-verify.js +4 -1
  16. package/cli/commands/keys-generate.js +12 -46
  17. package/cli/index.js +4 -7
  18. package/cli/package.json +2 -1
  19. package/dist/esm/core/config.d.ts +3 -0
  20. package/dist/esm/core/config.js +17 -0
  21. package/dist/esm/core/plugin-manager.js +4 -2
  22. package/dist/esm/core/security.js +2 -5
  23. package/dist/esm/core/update-check.d.ts +2 -0
  24. package/dist/esm/core/update-check.js +5 -3
  25. package/dist/esm/definitions.d.ts +43 -2
  26. package/dist/esm/live-update/delta-processor.d.ts +6 -20
  27. package/dist/esm/live-update/delta-processor.js +75 -119
  28. package/dist/esm/plugin.d.ts +0 -3
  29. package/dist/esm/plugin.js +172 -12
  30. package/dist/esm/security/crypto.js +2 -5
  31. package/dist/esm/web.d.ts +1 -9
  32. package/dist/esm/web.js +4 -56
  33. package/dist/plugin.cjs +1 -1
  34. package/dist/plugin.esm.js +1 -1
  35. package/dist/plugin.js +2 -2
  36. package/docs/CHANGELOG.md +49 -0
  37. package/docs/KNOWN_LIMITATIONS.md +4 -3
  38. package/docs/MIGRATION.md +32 -3
  39. package/docs/server-requirements.md +40 -29
  40. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +6 -2
  41. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +21 -30
  42. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +269 -61
  43. package/ios/Plugin/NativeUpdatePlugin.m +8 -1
  44. package/ios/Plugin/NativeUpdatePlugin.swift +71 -34
  45. package/ios/Plugin/Security/SecurityManager.swift +100 -99
  46. package/package.json +25 -13
@@ -26,7 +26,7 @@ class NativeUpdatePlugin : Plugin() {
26
26
  liveUpdatePlugin = LiveUpdatePlugin(activity, context)
27
27
  appUpdatePlugin = AppUpdatePlugin(activity, context)
28
28
  appReviewPlugin = AppReviewPlugin(activity, context)
29
- backgroundUpdatePlugin = BackgroundUpdatePlugin()
29
+ backgroundUpdatePlugin = BackgroundUpdatePlugin(context)
30
30
  securityManager = SecurityManager(context)
31
31
 
32
32
  // Set up app update event listener
@@ -46,6 +46,9 @@ class NativeUpdatePlugin : Plugin() {
46
46
  liveUpdatePlugin.setStateChangeListener { state ->
47
47
  notifyListeners("updateStateChanged", state)
48
48
  }
49
+ backgroundUpdatePlugin.setEventListener { event, data ->
50
+ notifyListeners(event, data)
51
+ }
49
52
 
50
53
  // Wire the WebView retargeting hook. set() calls this with the
51
54
  // extracted bundle's www/ path; we pass it to the Capacitor
@@ -77,15 +80,12 @@ class NativeUpdatePlugin : Plugin() {
77
80
  @PluginMethod
78
81
  fun initialize(call: PluginCall) {
79
82
  try {
80
- // Initialize with filesystem and preferences if provided
81
- // In Android, we typically don't need these as we use native APIs
82
-
83
- // Apply configuration. Both the wrapped ({ config: {...} }) and
84
- // the flat PluginInitConfig shapes are accepted — configure()
85
- // normalizes them (v3.1.3: the flat initialize() used to be
86
- // rejected here, so native never received serverUrl/apiKey).
87
- configure(call)
88
-
83
+ if (isInitialized) {
84
+ call.reject("Configuration is locked after initialization; call reset() first")
85
+ return
86
+ }
87
+ val config = call.getObject("config") ?: call.data
88
+ applyConfiguration(config)
89
89
  isInitialized = true
90
90
  call.resolve()
91
91
  } catch (e: Exception) {
@@ -118,42 +118,28 @@ class NativeUpdatePlugin : Plugin() {
118
118
  // configure(UpdateConfig) — nested sections
119
119
  // Before this fix, only the wrapped shape reached native, so the
120
120
  // flat initialize() every consumer uses configured NOTHING here.
121
- val config = call.getObject("config") ?: call.data
122
-
123
- if (config == null) {
124
- call.reject("Configuration object is required")
121
+ if (isInitialized) {
122
+ call.reject("Configuration is locked after initialization; call reset() first")
125
123
  return
126
124
  }
125
+ val config = call.getObject("config") ?: call.data
127
126
 
128
127
  try {
129
- // Validate security settings
130
- val securityConfig = config.getJSObject("security")
131
- if (securityConfig != null) {
132
- securityManager.configure(securityConfig)
133
- }
134
-
135
- // Configure sub-plugins
136
- val liveUpdateConfig = config.getJSObject("liveUpdate") ?: buildFlatLiveUpdateConfig(config)
137
- liveUpdateConfig?.let {
138
- liveUpdatePlugin.configure(it)
139
- }
140
-
141
- config.getJSObject("appUpdate")?.let {
142
- appUpdatePlugin.configure(it)
143
- }
144
-
145
- config.getJSObject("appReview")?.let {
146
- appReviewPlugin.configure(it)
147
- }
148
-
149
- // Background update configuration is handled separately via enableBackgroundUpdates
150
-
128
+ applyConfiguration(config)
129
+ isInitialized = true
151
130
  call.resolve()
152
131
  } catch (e: Exception) {
153
132
  call.reject("Configuration failed", e)
154
133
  }
155
134
  }
156
135
 
136
+ private fun applyConfiguration(config: JSObject) {
137
+ securityManager.configure(config)
138
+ normalizeLiveUpdateConfig(config)?.let(liveUpdatePlugin::configure)
139
+ config.getJSObject("appUpdate")?.let(appUpdatePlugin::configure)
140
+ config.getJSObject("appReview")?.let(appReviewPlugin::configure)
141
+ }
142
+
157
143
  /**
158
144
  * Normalize a flat PluginInitConfig (serverUrl/baseUrl, apiKey, appId,
159
145
  * channel, publicKey at the top level) into the liveUpdate config shape
@@ -173,9 +159,48 @@ class NativeUpdatePlugin : Plugin() {
173
159
  config.getString("appId")?.let { liveUpdate.put("appId", it) }
174
160
  config.getString("channel")?.let { liveUpdate.put("channel", it) }
175
161
  config.getString("publicKey")?.let { liveUpdate.put("publicKey", it) }
162
+ config.getBool("requireSignature")?.let { liveUpdate.put("requireSignature", it) }
163
+ config.getBool("allowUnsignedDevelopmentUpdates")?.let {
164
+ liveUpdate.put("allowUnsignedDevelopmentUpdates", it)
165
+ }
166
+ config.getString("checksumAlgorithm")?.let { liveUpdate.put("checksumAlgorithm", it) }
167
+ config.getLong("maxBundleSize")?.let { liveUpdate.put("maxBundleSize", it) }
168
+ config.getLong("maxUncompressedBundleSize")?.let {
169
+ liveUpdate.put("maxUncompressedBundleSize", it)
170
+ }
171
+ config.getBool("enableDeltaUpdates")?.let { liveUpdate.put("enableDeltaUpdates", it) }
172
+ config.getJSONArray("allowedHosts")?.let { liveUpdate.put("allowedHosts", it) }
176
173
  config.getJSObject("security")?.let { liveUpdate.put("security", it) }
177
174
  return liveUpdate
178
175
  }
176
+
177
+ /** Merge root security controls into both documented configuration shapes. */
178
+ private fun normalizeLiveUpdateConfig(config: JSObject): JSObject? {
179
+ val liveUpdate = config.getJSObject("liveUpdate") ?: buildFlatLiveUpdateConfig(config) ?: return null
180
+ if (!liveUpdate.has("security")) {
181
+ config.getJSObject("security")?.let { liveUpdate.put("security", it) }
182
+ }
183
+ if (!liveUpdate.has("publicKey")) {
184
+ config.getString("publicKey")?.let { liveUpdate.put("publicKey", it) }
185
+ }
186
+ if (!liveUpdate.has("requireSignature")) {
187
+ config.getBool("requireSignature")?.let { liveUpdate.put("requireSignature", it) }
188
+ }
189
+ if (!liveUpdate.has("allowUnsignedDevelopmentUpdates")) {
190
+ config.getBool("allowUnsignedDevelopmentUpdates")?.let {
191
+ liveUpdate.put("allowUnsignedDevelopmentUpdates", it)
192
+ }
193
+ }
194
+ if (!liveUpdate.has("maxUncompressedBundleSize")) {
195
+ config.getLong("maxUncompressedBundleSize")?.let {
196
+ liveUpdate.put("maxUncompressedBundleSize", it)
197
+ }
198
+ }
199
+ if (!liveUpdate.has("enableDeltaUpdates")) {
200
+ config.getBool("enableDeltaUpdates")?.let { liveUpdate.put("enableDeltaUpdates", it) }
201
+ }
202
+ return liveUpdate
203
+ }
179
204
 
180
205
  @PluginMethod
181
206
  fun getSecurityInfo(call: PluginCall) {
@@ -260,6 +285,18 @@ class NativeUpdatePlugin : Plugin() {
260
285
  fun validateUpdate(call: PluginCall) {
261
286
  liveUpdatePlugin.validateUpdate(call)
262
287
  }
288
+
289
+ @PluginMethod
290
+ fun cancelDownload(call: PluginCall) = liveUpdatePlugin.cancelDownload(call)
291
+
292
+ @PluginMethod
293
+ fun cancelAllDownloads(call: PluginCall) = liveUpdatePlugin.cancelAllDownloads(call)
294
+
295
+ @PluginMethod
296
+ fun isDownloading(call: PluginCall) = liveUpdatePlugin.isDownloading(call)
297
+
298
+ @PluginMethod
299
+ fun getActiveDownloadCount(call: PluginCall) = liveUpdatePlugin.getActiveDownloadCount(call)
263
300
 
264
301
  // App Update Methods
265
302
 
@@ -342,4 +379,4 @@ class NativeUpdatePlugin : Plugin() {
342
379
  backgroundUpdatePlugin.requestNotificationPermissions(call)
343
380
  }
344
381
 
345
- }
382
+ }
@@ -1,249 +1,239 @@
1
1
  package com.aoneahsan.nativeupdate
2
2
 
3
3
  import android.content.Context
4
+ import android.net.Uri
5
+ import android.security.keystore.KeyGenParameterSpec
6
+ import android.security.keystore.KeyProperties
4
7
  import android.util.Base64
5
- import androidx.security.crypto.EncryptedSharedPreferences
6
- import androidx.security.crypto.MasterKey
7
8
  import com.getcapacitor.JSObject
8
9
  import okhttp3.CertificatePinner
9
10
  import java.io.File
10
- import java.security.*
11
+ import java.security.KeyFactory
12
+ import java.security.KeyStore
13
+ import java.security.MessageDigest
14
+ import java.security.Signature
11
15
  import java.security.spec.X509EncodedKeySpec
12
16
  import javax.crypto.Cipher
17
+ import javax.crypto.KeyGenerator
18
+ import javax.crypto.SecretKey
19
+ import javax.crypto.spec.GCMParameterSpec
13
20
 
21
+ /** Security primitives shared by the Android update client. */
14
22
  class SecurityManager(private val context: Context) {
15
23
  private var config: JSObject? = null
16
- private val masterKey: MasterKey
17
- private val securePrefs: android.content.SharedPreferences
18
-
19
- init {
20
- // Initialize master key for encryption
21
- masterKey = MasterKey.Builder(context)
22
- .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
23
- .build()
24
-
25
- // Initialize encrypted shared preferences
26
- securePrefs = EncryptedSharedPreferences.create(
27
- context,
28
- "native_update_secure",
29
- masterKey,
30
- EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
31
- EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
32
- )
24
+ private val securePrefs = context.getSharedPreferences(SECURE_PREFS, Context.MODE_PRIVATE)
25
+
26
+ companion object {
27
+ private const val SECURE_PREFS = "native_update_secure_v2"
28
+ private const val KEY_ALIAS = "native_update_aes_gcm_v2"
29
+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"
30
+ private const val AES_TRANSFORMATION = "AES/GCM/NoPadding"
31
+ private const val GCM_IV_BYTES = 12
32
+ private const val GCM_TAG_BITS = 128
33
+ private val VALID_PIN = Regex("^sha256/[A-Za-z0-9+/]{43}=$")
33
34
  }
34
-
35
+
35
36
  fun configure(config: JSObject) {
36
37
  this.config = config
37
-
38
- // Validate security configuration
39
- val enforceHttps = config.getBool("enforceHttps") ?: true
40
- if (!enforceHttps) {
41
- // Log warning about disabled HTTPS enforcement
42
- android.util.Log.w("SecurityManager", "HTTPS enforcement is disabled. This is not recommended for production.")
38
+ val security = securityConfig()
39
+ require(security?.optBoolean("enforceHttps", true) != false) {
40
+ "HTTPS enforcement cannot be disabled"
41
+ }
42
+
43
+ val pinning = security?.takeIf { it.has("certificatePinning") }?.getJSObject("certificatePinning")
44
+ if (pinning?.getBool("enabled") == true) {
45
+ val pins = pinning.getJSONArray("pins")
46
+ require(pins != null && pins.length() > 0) {
47
+ "Certificate pinning requires at least one host pin"
48
+ }
49
+ for (index in 0 until pins.length()) {
50
+ val pin = pins.getJSONObject(index)
51
+ require(!pin.optString("hostname").isNullOrBlank()) {
52
+ "Certificate pin hostname is required"
53
+ }
54
+ val hashes = pin.optJSONArray("sha256")
55
+ require(hashes != null && hashes.length() > 0) {
56
+ "Certificate pin requires at least one SHA-256 hash"
57
+ }
58
+ for (hashIndex in 0 until hashes.length()) {
59
+ require(VALID_PIN.matches(hashes.getString(hashIndex))) {
60
+ "Certificate pins must use sha256/<base64> format"
61
+ }
62
+ }
63
+ }
43
64
  }
44
65
  }
45
-
66
+
46
67
  fun getSecurityInfo(): JSObject {
68
+ val security = securityConfig()
47
69
  val result = JSObject()
48
-
49
- result.put("enforceHttps", config?.getBool("enforceHttps") ?: true)
50
-
70
+ result.put("enforceHttps", true)
71
+
51
72
  val certificatePinning = JSObject()
52
- val pinningConfig = config?.getJSObject("certificatePinning")
73
+ val pinningConfig = security?.takeIf { it.has("certificatePinning") }?.getJSObject("certificatePinning")
53
74
  certificatePinning.put("enabled", pinningConfig?.getBool("enabled") ?: false)
54
-
55
- // Convert pins to proper format
56
75
  val pins = mutableListOf<JSObject>()
57
76
  val pinsArray = pinningConfig?.getJSONArray("pins")
58
77
  if (pinsArray != null) {
59
- for (i in 0 until pinsArray.length()) {
60
- val pin = pinsArray.getJSONObject(i)
61
- val pinObject = JSObject()
62
- pinObject.put("hostname", pin.getString("hostname"))
63
- pinObject.put("sha256", pin.getJSONArray("sha256"))
64
- pins.add(pinObject)
78
+ for (index in 0 until pinsArray.length()) {
79
+ val pin = pinsArray.getJSONObject(index)
80
+ pins.add(JSObject().apply {
81
+ put("hostname", pin.getString("hostname"))
82
+ put("sha256", pin.getJSONArray("sha256"))
83
+ })
65
84
  }
66
85
  }
67
86
  certificatePinning.put("pins", pins.toTypedArray())
68
87
  result.put("certificatePinning", certificatePinning)
69
-
70
- result.put("validateInputs", config?.getBool("validateInputs") ?: true)
71
- // Hard-coded true since v2 — secure storage is no longer opt-out.
88
+ result.put("validateInputs", security?.optBoolean("validateInputs", true) ?: true)
72
89
  result.put("secureStorage", true)
73
-
90
+ result.put("signatureAlgorithm", "RSA-SHA256")
74
91
  return result
75
92
  }
76
-
93
+
77
94
  fun validateUrl(url: String): Boolean {
78
- if (!url.startsWith("https://") && isHttpsEnforced()) {
95
+ val uri = try {
96
+ Uri.parse(url)
97
+ } catch (_: Exception) {
79
98
  return false
80
99
  }
81
-
82
- // Check against allowed hosts if configured
83
- val allowedHosts = getAllowedHosts()
84
- if (allowedHosts.isNotEmpty()) {
85
- val uri = android.net.Uri.parse(url)
86
- val host = uri.host ?: return false
87
- return allowedHosts.contains(host)
100
+ if (!uri.scheme.equals("https", ignoreCase = true) || uri.host.isNullOrBlank() || uri.userInfo != null) {
101
+ return false
88
102
  }
89
-
90
- return true
103
+ val allowedHosts = getAllowedHosts()
104
+ return allowedHosts.isEmpty() || allowedHosts.any { it.equals(uri.host, ignoreCase = true) }
91
105
  }
92
-
106
+
93
107
  fun getCertificatePinner(): CertificatePinner? {
94
- val pinningConfig = config?.getJSObject("certificatePinning") ?: return null
95
-
96
- if (pinningConfig.getBool("enabled") != true) {
97
- return null
98
- }
99
-
100
- val pins = pinningConfig.getJSONArray("pins") ?: return null
101
- if (pins.length() == 0) {
102
- return null
103
- }
104
-
108
+ val pinning = securityConfig()?.getJSObject("certificatePinning") ?: return null
109
+ if (pinning.getBool("enabled") != true) return null
110
+ val pins = pinning.getJSONArray("pins") ?: return null
105
111
  val builder = CertificatePinner.Builder()
106
-
107
- // Add certificate pins for each host
108
- for (i in 0 until pins.length()) {
109
- val pin = pins.getJSONObject(i)
112
+ for (index in 0 until pins.length()) {
113
+ val pin = pins.getJSONObject(index)
110
114
  val hostname = pin.getString("hostname") ?: continue
111
- val sha256Pins = pin.getJSONArray("sha256") ?: continue
112
-
113
- for (j in 0 until sha256Pins.length()) {
114
- val sha256Pin = sha256Pins.getString(j)
115
- builder.add(hostname, sha256Pin)
115
+ val hashes = pin.getJSONArray("sha256") ?: continue
116
+ for (hashIndex in 0 until hashes.length()) {
117
+ builder.add(hostname, hashes.getString(hashIndex))
116
118
  }
117
119
  }
118
-
119
120
  return builder.build()
120
121
  }
121
-
122
- fun verifySignature(data: ByteArray, signature: String, publicKeyString: String): Boolean {
122
+
123
+ /** Verify the backend's RSA-SHA256 (PKCS#1 v1.5) signature without loading the bundle into memory. */
124
+ fun verifySignature(file: File, signature: String, publicKeyString: String): Boolean {
123
125
  return try {
124
- // Handle PEM format or base64 encoded public key
125
- val publicKeyBase64 = if (publicKeyString.contains("-----BEGIN PUBLIC KEY-----")) {
126
- publicKeyString
127
- .replace("-----BEGIN PUBLIC KEY-----", "")
128
- .replace("-----END PUBLIC KEY-----", "")
129
- .replace("\n", "")
130
- .replace("\r", "")
131
- .trim()
132
- } else {
133
- publicKeyString
126
+ val publicKeyBase64 = publicKeyString
127
+ .replace("-----BEGIN PUBLIC KEY-----", "")
128
+ .replace("-----END PUBLIC KEY-----", "")
129
+ .replace(Regex("\\s"), "")
130
+ val publicKey = KeyFactory.getInstance("RSA").generatePublic(
131
+ X509EncodedKeySpec(Base64.decode(publicKeyBase64, Base64.DEFAULT))
132
+ )
133
+ val verifier = Signature.getInstance("SHA256withRSA")
134
+ verifier.initVerify(publicKey)
135
+ file.inputStream().use { input ->
136
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
137
+ while (true) {
138
+ val read = input.read(buffer)
139
+ if (read < 0) break
140
+ verifier.update(buffer, 0, read)
141
+ }
134
142
  }
135
-
136
- val publicKeyBytes = Base64.decode(publicKeyBase64, Base64.DEFAULT)
137
- val keySpec = X509EncodedKeySpec(publicKeyBytes)
138
- val keyFactory = KeyFactory.getInstance("RSA")
139
- val publicKey = keyFactory.generatePublic(keySpec)
140
-
141
- // Use RSA-PSS to match web implementation
142
- val sig = Signature.getInstance("SHA256withRSA/PSS")
143
- sig.initVerify(publicKey)
144
- sig.update(data)
145
-
146
- val signatureBytes = Base64.decode(signature, Base64.DEFAULT)
147
- sig.verify(signatureBytes)
148
- } catch (e: Exception) {
149
- android.util.Log.e("SecurityManager", "Signature verification failed", e)
143
+ verifier.verify(Base64.decode(signature, Base64.DEFAULT))
144
+ } catch (_: Exception) {
150
145
  false
151
146
  }
152
147
  }
153
-
148
+
154
149
  fun calculateChecksum(file: File, algorithm: String = "SHA-256"): String {
155
150
  val digest = MessageDigest.getInstance(algorithm)
156
151
  file.inputStream().use { input ->
157
- val buffer = ByteArray(8192)
158
- var read: Int
159
- while (input.read(buffer).also { read = it } != -1) {
152
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
153
+ while (true) {
154
+ val read = input.read(buffer)
155
+ if (read < 0) break
160
156
  digest.update(buffer, 0, read)
161
157
  }
162
158
  }
163
- return digest.digest().joinToString("") { "%02x".format(it) }
159
+ return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
164
160
  }
165
-
166
- /**
167
- * Writes always land in EncryptedSharedPreferences backed by the
168
- * Android Keystore master key. The old `secureStorage: false` opt-out
169
- * was removed in v2 — there is no legitimate reason to store an
170
- * API key or signing metadata in plaintext on a device, and shipping
171
- * the option was worse than not shipping it at all (the default was
172
- * opt-in, not opt-out, so most integrations landed in plaintext).
173
- */
161
+
162
+ /** Values are encrypted by a non-exportable AES-GCM key held in AndroidKeyStore. */
174
163
  fun saveSecureData(key: String, value: String) {
175
- securePrefs.edit().putString(key, value).apply()
164
+ val cipher = Cipher.getInstance(AES_TRANSFORMATION)
165
+ cipher.init(Cipher.ENCRYPT_MODE, getOrCreateSecretKey())
166
+ val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
167
+ require(cipher.iv.size == GCM_IV_BYTES)
168
+ val payload = cipher.iv + encrypted
169
+ securePrefs.edit().putString(key, Base64.encodeToString(payload, Base64.NO_WRAP)).apply()
176
170
  }
177
171
 
178
172
  fun getSecureData(key: String): String? {
179
- return securePrefs.getString(key, null)
173
+ val encoded = securePrefs.getString(key, null) ?: return null
174
+ return try {
175
+ val payload = Base64.decode(encoded, Base64.NO_WRAP)
176
+ if (payload.size <= GCM_IV_BYTES) return null
177
+ val iv = payload.copyOfRange(0, GCM_IV_BYTES)
178
+ val encrypted = payload.copyOfRange(GCM_IV_BYTES, payload.size)
179
+ val cipher = Cipher.getInstance(AES_TRANSFORMATION)
180
+ cipher.init(Cipher.DECRYPT_MODE, getOrCreateSecretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
181
+ String(cipher.doFinal(encrypted), Charsets.UTF_8)
182
+ } catch (_: Exception) {
183
+ null
184
+ }
180
185
  }
181
-
186
+
182
187
  fun validatePath(path: String): Boolean {
183
- // Prevent directory traversal attacks
184
- if (path.contains("..") || path.contains("//")) {
185
- return false
188
+ return try {
189
+ val candidate = File(path).canonicalFile
190
+ val root = context.filesDir.canonicalFile
191
+ candidate == root || candidate.path.startsWith(root.path + File.separator)
192
+ } catch (_: Exception) {
193
+ false
186
194
  }
187
-
188
- // Ensure path is within app's private directory
189
- val file = File(path)
190
- val canonicalPath = file.canonicalPath
191
- val appDir = context.filesDir.canonicalPath
192
-
193
- return canonicalPath.startsWith(appDir)
194
- }
195
-
196
- fun sanitizeInput(input: String): String {
197
- // Remove potentially dangerous characters
198
- return input.replace(Regex("[^a-zA-Z0-9._-]"), "")
199
195
  }
200
-
201
- fun isHttpsEnforced(): Boolean {
202
- return config?.getBool("enforceHttps") ?: true
203
- }
204
-
205
- /**
206
- * Secure storage is unconditionally on since v2. Kept as a getter so
207
- * `getSecurityInfo()` still reports accurately to callers.
208
- */
196
+
197
+ fun sanitizeInput(input: String): String = input.replace(Regex("[^a-zA-Z0-9._-]"), "")
198
+ fun isHttpsEnforced(): Boolean = true
209
199
  fun isSecureStorageEnabled(): Boolean = true
210
-
211
- fun isInputValidationEnabled(): Boolean {
212
- return config?.getBool("validateInputs") ?: true
200
+ fun isInputValidationEnabled(): Boolean = securityConfig()?.optBoolean("validateInputs", true) ?: true
201
+
202
+ fun logSecurityEvent(event: String, details: String? = null) {
203
+ if (securityConfig()?.optBoolean("logSecurityEvents", false) == true) {
204
+ android.util.Log.i("NativeUpdateSecurity", "$event ${details ?: ""}".trim())
205
+ }
213
206
  }
214
-
207
+
208
+ private fun securityConfig(): JSObject? = config?.let {
209
+ if (it.has("security")) it.getJSObject("security") else it
210
+ }
211
+
215
212
  private fun getAllowedHosts(): List<String> {
216
213
  val hosts = mutableListOf<String>()
217
-
218
- // Add hosts from certificate pinning config
219
- val pinningConfig = config?.getJSObject("certificatePinning")
220
- if (pinningConfig != null) {
221
- // In a real implementation, we'd extract hosts from the configuration
222
- // For now, we'll use the server URL
223
- val serverUrl = config?.getString("serverUrl")
224
- if (serverUrl != null) {
225
- val uri = android.net.Uri.parse(serverUrl)
226
- uri.host?.let { hosts.add(it) }
227
- }
228
- }
229
-
230
- // Add allowed hosts from live update config
231
- val liveUpdateConfig = config?.getJSObject("liveUpdate")
232
- val allowedHosts = liveUpdateConfig?.getJSONArray("allowedHosts")
233
- if (allowedHosts != null) {
234
- for (i in 0 until allowedHosts.length()) {
235
- hosts.add(allowedHosts.getString(i))
236
- }
214
+ val allowed = config?.optJSONArray("allowedHosts")
215
+ ?: config?.optJSONObject("liveUpdate")?.optJSONArray("allowedHosts")
216
+ if (allowed != null) {
217
+ for (index in 0 until allowed.length()) hosts.add(allowed.getString(index))
237
218
  }
238
-
239
- return hosts.distinct()
219
+ return hosts.map { it.lowercase() }.distinct()
240
220
  }
241
-
242
- fun logSecurityEvent(event: String, details: String? = null) {
243
- if (config?.getBool("logSecurityEvents") == true) {
244
- android.util.Log.i("SecurityManager", "Security Event: $event ${details ?: ""}")
245
-
246
- // In production, you might want to send these to a security monitoring service
247
- }
221
+
222
+ private fun getOrCreateSecretKey(): SecretKey {
223
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
224
+ (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
225
+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
226
+ generator.init(
227
+ KeyGenParameterSpec.Builder(
228
+ KEY_ALIAS,
229
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
230
+ )
231
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
232
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
233
+ .setKeySize(256)
234
+ .setRandomizedEncryptionRequired(true)
235
+ .build()
236
+ )
237
+ return generator.generateKey()
248
238
  }
249
- }
239
+ }
@@ -1,5 +1,5 @@
1
1
  ext {
2
- kotlinVersion = project.hasProperty('kotlinVersion') ? rootProject.ext.kotlinVersion : '1.9.22'
2
+ kotlinVersion = project.hasProperty('kotlinVersion') ? rootProject.ext.kotlinVersion : '2.2.20'
3
3
  playAppUpdateVersion = '2.1.0'
4
4
  playReviewVersion = '2.0.1'
5
- }
5
+ }
@@ -20,6 +20,9 @@ export async function verifyBundle(bundlePath, options) {
20
20
  } catch {
21
21
  throw new Error(`No signature file found at ${sigPath}`);
22
22
  }
23
+ if (signatureData.algorithm !== 'RSA-SHA256' || typeof signatureData.signature !== 'string') {
24
+ throw new Error('Signature metadata must use RSA-SHA256');
25
+ }
23
26
 
24
27
  // Read public key
25
28
  const publicKeyPem = await fs.readFile(options.key, 'utf-8');
@@ -52,4 +55,4 @@ export async function verifyBundle(bundlePath, options) {
52
55
  console.error(chalk.red('❌ Failed to verify bundle:'), error.message);
53
56
  process.exit(1);
54
57
  }
55
- }
58
+ }