native-update 3.4.1 → 4.0.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 (48) hide show
  1. package/AI-INTEGRATION-GUIDE.md +26 -16
  2. package/NativeUpdate.podspec +2 -2
  3. package/README.md +554 -0
  4. package/android/build.gradle +43 -34
  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/.yarn/install-state.gz +0 -0
  16. package/cli/commands/bundle-verify.js +4 -1
  17. package/cli/commands/keys-generate.js +12 -46
  18. package/cli/index.js +4 -7
  19. package/cli/package.json +2 -1
  20. package/dist/esm/core/config.d.ts +3 -0
  21. package/dist/esm/core/config.js +17 -0
  22. package/dist/esm/core/plugin-manager.js +4 -2
  23. package/dist/esm/core/security.js +2 -5
  24. package/dist/esm/core/update-check.d.ts +2 -0
  25. package/dist/esm/core/update-check.js +5 -3
  26. package/dist/esm/definitions.d.ts +43 -2
  27. package/dist/esm/live-update/delta-processor.d.ts +6 -20
  28. package/dist/esm/live-update/delta-processor.js +75 -119
  29. package/dist/esm/plugin.d.ts +0 -3
  30. package/dist/esm/plugin.js +172 -12
  31. package/dist/esm/security/crypto.js +2 -5
  32. package/dist/esm/web.d.ts +1 -9
  33. package/dist/esm/web.js +4 -56
  34. package/dist/plugin.cjs +1 -1
  35. package/dist/plugin.esm.js +1 -1
  36. package/dist/plugin.js +2 -2
  37. package/docs/CHANGELOG.md +66 -0
  38. package/docs/KNOWN_LIMITATIONS.md +4 -3
  39. package/docs/MIGRATION.md +32 -3
  40. package/docs/server-requirements.md +40 -29
  41. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +6 -2
  42. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +21 -30
  43. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +269 -61
  44. package/ios/Plugin/NativeUpdatePlugin.m +8 -1
  45. package/ios/Plugin/NativeUpdatePlugin.swift +71 -34
  46. package/ios/Plugin/Security/SecurityManager.swift +100 -99
  47. package/package.json +27 -15
  48. package/Readme.md +0 -565
@@ -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
+ }
Binary file
@@ -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
+ }
@@ -1,7 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import fs from 'fs/promises';
3
3
  import path from 'path';
4
- import crypto from 'crypto';
5
4
  import { generateKeyPairSync } from 'crypto';
6
5
 
7
6
  export async function generateKeys(options) {
@@ -12,51 +11,18 @@ export async function generateKeys(options) {
12
11
  const outputDir = path.resolve(options.output);
13
12
  await fs.mkdir(outputDir, { recursive: true });
14
13
 
15
- let publicKey, privateKey;
16
-
17
- if (options.type === 'rsa') {
18
- // Generate RSA key pair
19
- const keySize = parseInt(options.size);
20
- if (![2048, 4096].includes(keySize)) {
21
- throw new Error('RSA key size must be 2048 or 4096');
22
- }
23
-
24
- ({ publicKey, privateKey } = generateKeyPairSync('rsa', {
25
- modulusLength: keySize,
26
- publicKeyEncoding: {
27
- type: 'spki',
28
- format: 'pem'
29
- },
30
- privateKeyEncoding: {
31
- type: 'pkcs8',
32
- format: 'pem'
33
- }
34
- }));
35
- } else if (options.type === 'ec') {
36
- // Generate EC key pair
37
- const curveMap = {
38
- '256': 'prime256v1',
39
- '384': 'secp384r1'
40
- };
41
- const namedCurve = curveMap[options.size];
42
- if (!namedCurve) {
43
- throw new Error('EC key size must be 256 or 384');
44
- }
45
-
46
- ({ publicKey, privateKey } = generateKeyPairSync('ec', {
47
- namedCurve,
48
- publicKeyEncoding: {
49
- type: 'spki',
50
- format: 'pem'
51
- },
52
- privateKeyEncoding: {
53
- type: 'pkcs8',
54
- format: 'pem'
55
- }
56
- }));
57
- } else {
58
- throw new Error('Key type must be "rsa" or "ec"');
14
+ if (options.type !== 'rsa') {
15
+ throw new Error('Only RSA keys are supported by the RSA-SHA256 bundle contract');
16
+ }
17
+ const keySize = parseInt(options.size);
18
+ if (![2048, 4096].includes(keySize)) {
19
+ throw new Error('RSA key size must be 2048 or 4096');
59
20
  }
21
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', {
22
+ modulusLength: keySize,
23
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
24
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
25
+ });
60
26
 
61
27
  // Save keys
62
28
  const timestamp = Date.now();
@@ -89,4 +55,4 @@ export async function generateKeys(options) {
89
55
  console.error(chalk.red('❌ Failed to generate keys:'), error.message);
90
56
  process.exit(1);
91
57
  }
92
- }
58
+ }
package/cli/index.js CHANGED
@@ -120,13 +120,10 @@ ${chalk.bold('Examples:')}
120
120
  ${chalk.green('npx native-update keys generate')}
121
121
 
122
122
  ${chalk.gray('# Generate strong RSA 4096-bit keys for production')}
123
- ${chalk.green('npx native-update keys generate --type rsa --size 4096')}
124
-
125
- ${chalk.gray('# Generate EC keys for smaller signatures')}
126
- ${chalk.green('npx native-update keys generate --type ec --size 256 --output ./my-keys')}`)
123
+ ${chalk.green('npx native-update keys generate --type rsa --size 4096 --output ./my-keys')}`)
127
124
  .option('-o, --output <dir>', 'Output directory for keys', './keys')
128
- .option('-t, --type <type>', 'Key type (rsa or ec)', 'rsa')
129
- .option('-s, --size <size>', 'Key size (RSA: 2048/4096, EC: 256/384)', '2048')
125
+ .option('-t, --type <type>', 'Key type (rsa)', 'rsa')
126
+ .option('-s, --size <size>', 'RSA key size (2048 or 4096)', '2048')
130
127
  .action(async (options) => {
131
128
  const { generateKeys } = await import('./commands/keys-generate.js');
132
129
  await generateKeys(options);
@@ -599,4 +596,4 @@ try {
599
596
  console.error(chalk.red(`Error: ${error.message}`));
600
597
  }
601
598
  process.exit(error.exitCode ?? 1);
602
- }
599
+ }
package/cli/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "native-update-cli",
3
3
  "private": true,
4
+ "packageManager": "yarn@4.17.0",
4
5
  "description": "CLI for Native Update. No version field on purpose: the CLI ships inside the native-update npm package and reads its version from the ROOT package.json (single source of truth) via cli/index.js.",
5
6
  "type": "module",
6
7
  "engines": {
@@ -14,7 +15,7 @@
14
15
  "chalk": "^5.6.2",
15
16
  "commander": "^15.0.0",
16
17
  "express": "^5.2.1",
17
- "ora": "^9.4.0",
18
+ "ora": "^9.4.1",
18
19
  "prompts": "^2.4.2"
19
20
  }
20
21
  }
@@ -7,6 +7,7 @@ export interface PluginConfig {
7
7
  baseUrl?: string;
8
8
  allowedHosts?: string[];
9
9
  maxBundleSize?: number;
10
+ maxUncompressedBundleSize?: number;
10
11
  downloadTimeout?: number;
11
12
  retryAttempts?: number;
12
13
  retryDelay?: number;
@@ -31,6 +32,7 @@ export interface PluginConfig {
31
32
  checksumAlgorithm?: ChecksumAlgorithm;
32
33
  checkInterval?: number;
33
34
  security?: SecurityConfig;
35
+ allowUnsignedDevelopmentUpdates?: boolean;
34
36
  promptAfterPositiveEvents?: boolean;
35
37
  maxPromptsPerVersion?: number;
36
38
  minimumDaysSinceLastPrompt?: number;
@@ -58,6 +60,7 @@ export declare class ConfigManager {
58
60
  static getInstance(): ConfigManager;
59
61
  private getDefaultConfig;
60
62
  configure(config: PluginConfig): void;
63
+ reset(): void;
61
64
  private validateConfig;
62
65
  get<K extends keyof Required<PluginConfig>>(key: K): Required<PluginConfig>[K];
63
66
  set<K extends keyof Required<PluginConfig>>(key: K, value: Required<PluginConfig>[K]): void;
@@ -15,6 +15,7 @@ export class ConfigManager {
15
15
  baseUrl: '',
16
16
  allowedHosts: [],
17
17
  maxBundleSize: 100 * 1024 * 1024, // 100MB
18
+ maxUncompressedBundleSize: 500 * 1024 * 1024, // 500MB
18
19
  downloadTimeout: 30000, // 30 seconds
19
20
  retryAttempts: 3,
20
21
  retryDelay: 1000, // 1 second
@@ -38,6 +39,7 @@ export class ConfigManager {
38
39
  secureStorage: true,
39
40
  logSecurityEvents: false,
40
41
  },
42
+ allowUnsignedDevelopmentUpdates: false,
41
43
  // App review config
42
44
  promptAfterPositiveEvents: false,
43
45
  maxPromptsPerVersion: 1,
@@ -57,6 +59,9 @@ export class ConfigManager {
57
59
  this.config = Object.assign(Object.assign({}, this.config), config);
58
60
  this.validateConfig();
59
61
  }
62
+ reset() {
63
+ this.config = this.getDefaultConfig();
64
+ }
60
65
  validateConfig() {
61
66
  // Validate HTTPS for baseUrl (security requirement)
62
67
  if (this.config.baseUrl && !this.config.baseUrl.startsWith('https://')) {
@@ -65,6 +70,9 @@ export class ConfigManager {
65
70
  if (this.config.maxBundleSize <= 0) {
66
71
  throw new Error('maxBundleSize must be greater than 0');
67
72
  }
73
+ if (this.config.maxUncompressedBundleSize <= 0) {
74
+ throw new Error('maxUncompressedBundleSize must be greater than 0');
75
+ }
68
76
  if (this.config.downloadTimeout <= 0) {
69
77
  throw new Error('downloadTimeout must be greater than 0');
70
78
  }
@@ -74,6 +82,15 @@ export class ConfigManager {
74
82
  if (this.config.retryDelay < 0) {
75
83
  throw new Error('retryDelay must be non-negative');
76
84
  }
85
+ if (this.config.security.enforceHttps === false) {
86
+ throw new Error('HTTPS enforcement cannot be disabled');
87
+ }
88
+ if ((this.config.serverUrl || this.config.apiKey) && this.config.requireSignature && !this.config.publicKey) {
89
+ throw new Error('publicKey is required when requireSignature is enabled');
90
+ }
91
+ if (!this.config.requireSignature && !this.config.allowUnsignedDevelopmentUpdates) {
92
+ throw new Error('Disabling signatures requires allowUnsignedDevelopmentUpdates for an explicit development-only setup');
93
+ }
77
94
  }
78
95
  get(key) {
79
96
  return this.config[key];