native-update-react-native 0.0.0-stage → 1.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.
- package/LICENSE +25 -0
- package/README.md +82 -2
- package/android/build.gradle +40 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/Errors.kt +20 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/NativeUpdate.kt +309 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/NativeUpdateConfig.kt +92 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/PlayAppUpdate.kt +153 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/PlayReview.kt +68 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/UpdateTypes.kt +50 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/AppInfo.kt +56 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/BundleStore.kt +210 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/BundleVerifier.kt +66 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/UpdateClient.kt +179 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/Versions.kt +34 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/android/internal/ZipExtractor.kt +55 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdateModule.kt +155 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdatePackage.kt +30 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/reactnative/NativeUpdateReactNative.kt +41 -0
- package/lib/NativeNativeUpdate.d.ts +16 -0
- package/lib/NativeNativeUpdate.js +4 -0
- package/lib/index.d.ts +72 -0
- package/lib/index.js +76 -0
- package/package.json +56 -4
- package/react-native.config.js +11 -0
- package/src/NativeNativeUpdate.ts +18 -0
- package/src/index.ts +111 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Native Update License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 Ahsan Mahmood. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This license applies to the native-update package from version 4.1.2 onward. Versions published before
|
|
6
|
+
4.1.2 remain available under the license they were published with.
|
|
7
|
+
|
|
8
|
+
1. Use. You may install the native-update package and use it, without charge, inside applications you
|
|
9
|
+
build and distribute, to receive updates from the Native Update service
|
|
10
|
+
(https://nativeupdate.aoneahsan.com) under a Native Update account and plan, or from a server you
|
|
11
|
+
operate that implements the update contract documented at https://nativeupdate-docs.aoneahsan.com.
|
|
12
|
+
|
|
13
|
+
2. Restrictions. You may not sell, sublicense, or redistribute the package or any part of it on its own
|
|
14
|
+
or as part of a library, SDK, or service that offers over-the-air update delivery to others; publish
|
|
15
|
+
a modified copy of it; or remove this notice. Shipping the package inside your own application
|
|
16
|
+
binaries and web bundles, as step 1 describes, is not redistribution under this section.
|
|
17
|
+
|
|
18
|
+
3. The service. Use of the Native Update service, dashboard, API, and CLI is governed by the Terms of
|
|
19
|
+
Service at https://nativeupdate.aoneahsan.com/terms.
|
|
20
|
+
|
|
21
|
+
4. No warranty. THE PACKAGE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
22
|
+
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
23
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
|
|
24
|
+
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
25
|
+
CONNECTION WITH THE PACKAGE OR THE USE OR OTHER DEALINGS IN THE PACKAGE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# native-update-react-native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Signed over-the-air **JavaScript bundle** updates, Google Play in-app update and in-app review for React Native. It
|
|
4
|
+
runs on the same Native Update account and licence as the Capacitor, Android and Flutter SDKs.
|
|
5
|
+
|
|
6
|
+
| | |
|
|
7
|
+
|---|---|
|
|
8
|
+
| Version | `1.0.0` |
|
|
9
|
+
| React Native | 0.80 or newer (New Architecture, TurboModule) |
|
|
10
|
+
| Android | minSdk 26 |
|
|
11
|
+
| iOS | not yet: the package links on Android only for now |
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
yarn add native-update-react-native
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Start the SDK natively, before React loads, so a bundle that breaks the app can still be rolled back. Then load
|
|
20
|
+
the active OTA bundle when there is one:
|
|
21
|
+
|
|
22
|
+
```kotlin
|
|
23
|
+
// android/app/src/main/java/.../MainApplication.kt
|
|
24
|
+
class MainApplication : Application(), ReactApplication {
|
|
25
|
+
override val reactHost: ReactHost by lazy {
|
|
26
|
+
getDefaultReactHost(
|
|
27
|
+
context = applicationContext,
|
|
28
|
+
packageList = PackageList(this).packages,
|
|
29
|
+
jsBundleFilePath = NativeUpdateReactNative.bundleFile(), // null = the bundle built into the APK
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
override fun onCreate() {
|
|
34
|
+
NativeUpdateReactNative.init(
|
|
35
|
+
this,
|
|
36
|
+
NativeUpdateConfig.Builder(
|
|
37
|
+
"https://nativeupdatebe.aoneahsan.com/api",
|
|
38
|
+
BuildConfig.NU_API_KEY, // the app's nu_app_ key
|
|
39
|
+
BuildConfig.NU_PUBLIC_KEY, // verifies every bundle
|
|
40
|
+
).build(),
|
|
41
|
+
)
|
|
42
|
+
super.onCreate()
|
|
43
|
+
loadReactNative(this)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Use
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import * as NativeUpdate from 'native-update-react-native';
|
|
52
|
+
|
|
53
|
+
// Once the app has rendered and works, on every start:
|
|
54
|
+
await NativeUpdate.notifyAppReady();
|
|
55
|
+
|
|
56
|
+
const result = await NativeUpdate.checkForUpdate();
|
|
57
|
+
if (result.type === 'available') {
|
|
58
|
+
await NativeUpdate.download(result.info); // runs from the next cold start
|
|
59
|
+
// or: await NativeUpdate.download(result.info, 'now'); NativeUpdate.restart();
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Publish a bundle
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
npx react-native bundle --platform android --dev false --entry-file index.js \
|
|
67
|
+
--bundle-output out/index.android.bundle --assets-dest out
|
|
68
|
+
node_modules/hermes-compiler/hermesc/linux64-bin/hermesc -O -emit-binary \
|
|
69
|
+
-out out/index.android.bundle.hbc out/index.android.bundle && mv out/index.android.bundle.hbc out/index.android.bundle
|
|
70
|
+
npx native-update deploy ./out --app com.example.app --version 1.0.1 --min-native 1.0.0 --wait
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Set `--min-native` to the app version the bundle was built against. A bundle needs the native modules it calls,
|
|
74
|
+
so a release that adds or changes native code goes through the store.
|
|
75
|
+
|
|
76
|
+
## What it guarantees
|
|
77
|
+
|
|
78
|
+
- **Integrity:** a bundle runs only after its SHA-256 matches and its RSA-SHA256 signature verifies. Both are
|
|
79
|
+
checked again on every cold start, before React loads.
|
|
80
|
+
- **Rollback:** a new bundle that hasn't reached `notifyAppReady()` within two cold starts is rolled back to the
|
|
81
|
+
previous one, and that bundle is never offered to that device again.
|
|
82
|
+
- **New binary:** a store update retires bundles made for the older build.
|
|
83
|
+
- **Payload safety:** the server only offers a React Native app JavaScript bundles, never a native asset set.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// React Native 0.80+ (New Architecture). src/main/java/com/aoneahsan/nativeupdate/android is the shared Kotlin core,
|
|
2
|
+
// copied from sdk/android by `yarn sync:android-core` at the repo root; `yarn check:android-core` fails on drift.
|
|
3
|
+
def ext(name, fallback) { return rootProject.ext.has(name) ? rootProject.ext.get(name) : fallback }
|
|
4
|
+
|
|
5
|
+
apply plugin: "com.android.library"
|
|
6
|
+
|
|
7
|
+
def agpMajor = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize(".")[0].toInteger()
|
|
8
|
+
// AGP 9 compiles Kotlin itself unless the app sets android.builtInKotlin=false (React Native's template does).
|
|
9
|
+
// Compared as a string on purpose: Groovy's `?:` would turn an explicit false into the default.
|
|
10
|
+
def builtInKotlinSetting = providers.gradleProperty("android.builtInKotlin").orNull
|
|
11
|
+
def builtInKotlin = agpMajor >= 9 && builtInKotlinSetting != "false"
|
|
12
|
+
if (!builtInKotlin) {
|
|
13
|
+
apply plugin: "kotlin-android"
|
|
14
|
+
}
|
|
15
|
+
apply plugin: "com.facebook.react"
|
|
16
|
+
|
|
17
|
+
android {
|
|
18
|
+
namespace "com.aoneahsan.nativeupdate.reactnative"
|
|
19
|
+
compileSdkVersion ext("compileSdkVersion", 36)
|
|
20
|
+
defaultConfig {
|
|
21
|
+
minSdkVersion Math.max(26, ext("minSdkVersion", 26) as int)
|
|
22
|
+
}
|
|
23
|
+
compileOptions {
|
|
24
|
+
sourceCompatibility JavaVersion.VERSION_17
|
|
25
|
+
targetCompatibility JavaVersion.VERSION_17
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
repositories {
|
|
30
|
+
google()
|
|
31
|
+
mavenCentral()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
dependencies {
|
|
35
|
+
implementation "com.facebook.react:react-android"
|
|
36
|
+
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0"
|
|
37
|
+
implementation "androidx.activity:activity:1.13.0"
|
|
38
|
+
implementation "com.google.android.play:app-update-ktx:2.1.0"
|
|
39
|
+
implementation "com.google.android.play:review:2.0.2"
|
|
40
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
/** Error codes shared with every Native Update SDK (docs/protocol/CLIENT-PROTOCOL.md §6). */
|
|
4
|
+
public object ErrorCodes {
|
|
5
|
+
public const val NETWORK_ERROR: String = "NETWORK_ERROR"
|
|
6
|
+
public const val DOWNLOAD_ERROR: String = "DOWNLOAD_ERROR"
|
|
7
|
+
public const val CHECKSUM_ERROR: String = "CHECKSUM_ERROR"
|
|
8
|
+
public const val SIGNATURE_ERROR: String = "SIGNATURE_ERROR"
|
|
9
|
+
public const val EXTRACTION_ERROR: String = "EXTRACTION_ERROR"
|
|
10
|
+
public const val INSECURE_URL: String = "INSECURE_URL"
|
|
11
|
+
public const val VALIDATION_ERROR: String = "VALIDATION_ERROR"
|
|
12
|
+
public const val NOT_INITIALIZED: String = "NOT_INITIALIZED"
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A failure the host app can act on. [code] is one of [ErrorCodes]; the message never holds paths or keys. */
|
|
16
|
+
public class NativeUpdateException(
|
|
17
|
+
public val code: String,
|
|
18
|
+
message: String,
|
|
19
|
+
cause: Throwable? = null,
|
|
20
|
+
) : Exception(message, cause)
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
import android.annotation.SuppressLint
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.os.Handler
|
|
6
|
+
import android.os.Looper
|
|
7
|
+
import android.util.Log
|
|
8
|
+
import com.aoneahsan.nativeupdate.android.internal.AppInfo
|
|
9
|
+
import com.aoneahsan.nativeupdate.android.internal.BundleStore
|
|
10
|
+
import com.aoneahsan.nativeupdate.android.internal.BundleVerifier
|
|
11
|
+
import com.aoneahsan.nativeupdate.android.internal.ClientIdentity
|
|
12
|
+
import com.aoneahsan.nativeupdate.android.internal.UpdateClient
|
|
13
|
+
import com.aoneahsan.nativeupdate.android.internal.Versions
|
|
14
|
+
import com.aoneahsan.nativeupdate.android.internal.ZipExtractor
|
|
15
|
+
import kotlinx.coroutines.CoroutineScope
|
|
16
|
+
import kotlinx.coroutines.Dispatchers
|
|
17
|
+
import kotlinx.coroutines.SupervisorJob
|
|
18
|
+
import kotlinx.coroutines.launch
|
|
19
|
+
import kotlinx.coroutines.withContext
|
|
20
|
+
import java.io.File
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Signed over-the-air asset updates for a native Android app.
|
|
24
|
+
*
|
|
25
|
+
* A bundle is a ZIP of files the app reads (images, JSON config, copy), never code. Every bundle is checked against
|
|
26
|
+
* its SHA-256 and RSA-SHA256 signature before it is used and again on every cold start. A bundle that does not reach
|
|
27
|
+
* [notifyAppReady] within two cold starts is rolled back. Protocol: `docs/protocol/CLIENT-PROTOCOL.md`.
|
|
28
|
+
*
|
|
29
|
+
* ```kotlin
|
|
30
|
+
* // Application.onCreate
|
|
31
|
+
* NativeUpdate.init(this, config)
|
|
32
|
+
* // once the first screen is up and working
|
|
33
|
+
* NativeUpdate.notifyAppReady()
|
|
34
|
+
* // reading a file that may have been updated, falling back to the one in the APK
|
|
35
|
+
* val flags = NativeUpdate.file("config/flags.json")?.readText() ?: assets.open("config/flags.json").reader().readText()
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
public object NativeUpdate {
|
|
39
|
+
/** This SDK's version, sent as `X-Sdk-Version`. Must equal the Gradle `VERSION_NAME` (checked by the build). */
|
|
40
|
+
public const val SDK_VERSION: String = "1.0.0"
|
|
41
|
+
|
|
42
|
+
private const val TAG = "NativeUpdate"
|
|
43
|
+
|
|
44
|
+
private class State(
|
|
45
|
+
val context: Context,
|
|
46
|
+
val config: NativeUpdateConfig,
|
|
47
|
+
val clientSdk: String,
|
|
48
|
+
val sdkVersion: String,
|
|
49
|
+
val store: BundleStore,
|
|
50
|
+
val client: UpdateClient,
|
|
51
|
+
val binary: String,
|
|
52
|
+
val builtInVersion: String,
|
|
53
|
+
val debuggable: Boolean,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
// Holds only the application context (init() calls applicationContext), which lives as long as the process.
|
|
57
|
+
@SuppressLint("StaticFieldLeak")
|
|
58
|
+
@Volatile
|
|
59
|
+
private var state: State? = null
|
|
60
|
+
|
|
61
|
+
@Volatile private var droppedReason: String? = null
|
|
62
|
+
|
|
63
|
+
private val javaScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
64
|
+
private val mainThread = Handler(Looper.getMainLooper())
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Starts the SDK. Call once, early (Application.onCreate), before reading any updated file. Runs the cold-start
|
|
68
|
+
* checks on the calling thread: one SHA-256 and signature check of the active bundle.
|
|
69
|
+
*
|
|
70
|
+
* Calling it again with an identical configuration does nothing; a different one is refused until [reset].
|
|
71
|
+
* [clientSdk] and [sdkVersion] are for the Flutter and React Native wrappers; apps leave them out.
|
|
72
|
+
*/
|
|
73
|
+
@JvmStatic
|
|
74
|
+
@JvmOverloads
|
|
75
|
+
@Synchronized
|
|
76
|
+
public fun init(
|
|
77
|
+
context: Context,
|
|
78
|
+
config: NativeUpdateConfig,
|
|
79
|
+
clientSdk: String = "android",
|
|
80
|
+
sdkVersion: String = SDK_VERSION,
|
|
81
|
+
) {
|
|
82
|
+
state?.let { current ->
|
|
83
|
+
if (current.config.fingerprint() == config.fingerprint() && current.clientSdk == clientSdk) return
|
|
84
|
+
throw NativeUpdateException(
|
|
85
|
+
ErrorCodes.VALIDATION_ERROR,
|
|
86
|
+
"Configuration is locked after initialization; call reset() first",
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
val app = context.applicationContext
|
|
90
|
+
val debuggable = AppInfo.isDebuggable(app)
|
|
91
|
+
if (NativeUpdateConfig.isLoopbackHttp(config.serverUrl) && !debuggable) {
|
|
92
|
+
throw NativeUpdateException(ErrorCodes.INSECURE_URL, "A plain-http test server is allowed only in debug builds")
|
|
93
|
+
}
|
|
94
|
+
val store = BundleStore(app)
|
|
95
|
+
val binary = AppInfo.binaryIdentity(app)
|
|
96
|
+
val fresh =
|
|
97
|
+
State(
|
|
98
|
+
context = app,
|
|
99
|
+
config = config,
|
|
100
|
+
clientSdk = clientSdk,
|
|
101
|
+
sdkVersion = sdkVersion,
|
|
102
|
+
store = store,
|
|
103
|
+
client = UpdateClient(allowLoopbackHttp = debuggable),
|
|
104
|
+
binary = binary,
|
|
105
|
+
builtInVersion = config.builtInVersion ?: AppInfo.versionName(app) ?: "0.0.0",
|
|
106
|
+
debuggable = debuggable,
|
|
107
|
+
)
|
|
108
|
+
droppedReason = store.onColdStart(binary) { id -> verifyStored(fresh, id) }
|
|
109
|
+
droppedReason?.let { reason ->
|
|
110
|
+
val now = if (store.activeId != null) "the previous update" else "the files built into the app"
|
|
111
|
+
Log.w(TAG, "Updated files were set aside because $reason; using $now.")
|
|
112
|
+
}
|
|
113
|
+
state = fresh
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** True once [init] has run in this process. */
|
|
117
|
+
@JvmStatic
|
|
118
|
+
public fun isInitialized(): Boolean = state != null
|
|
119
|
+
|
|
120
|
+
/** Why the last cold start set a bundle aside (rollback, failed check, new binary), or null. */
|
|
121
|
+
@JvmStatic
|
|
122
|
+
public fun lastDroppedReason(): String? = droppedReason
|
|
123
|
+
|
|
124
|
+
/** Version of the files in use: the active bundle's, or the one shipped in the APK. */
|
|
125
|
+
@JvmStatic
|
|
126
|
+
public fun currentVersion(): String {
|
|
127
|
+
val current = require()
|
|
128
|
+
return current.store.activeId?.let { current.store.versionOf(it) } ?: current.builtInVersion
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Directory of the active bundle's files, or null while the APK's own files are in use. */
|
|
132
|
+
@JvmStatic
|
|
133
|
+
public fun currentBundleDir(): File? = require().store.activeId?.let { require().store.directoryOf(it) }
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The updated copy of [relativePath] (for example `config/flags.json`), or null when the active bundle does not
|
|
137
|
+
* contain it or no bundle is active. The app then uses the copy inside its APK.
|
|
138
|
+
*/
|
|
139
|
+
@JvmStatic
|
|
140
|
+
public fun file(relativePath: String): File? {
|
|
141
|
+
val dir = currentBundleDir() ?: return null
|
|
142
|
+
val root = dir.canonicalFile
|
|
143
|
+
val candidate = File(root, relativePath).canonicalFile
|
|
144
|
+
if (!candidate.path.startsWith(root.path + File.separator)) return null
|
|
145
|
+
return candidate.takeIf { it.isFile }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Asks the server whether a newer bundle exists for this device. Network errors throw [NativeUpdateException]. */
|
|
149
|
+
public suspend fun checkForUpdate(): UpdateCheckResult =
|
|
150
|
+
withContext(Dispatchers.IO) {
|
|
151
|
+
val current = require()
|
|
152
|
+
val identity =
|
|
153
|
+
ClientIdentity(
|
|
154
|
+
apiKey = current.config.apiKey,
|
|
155
|
+
deviceId = current.store.deviceId,
|
|
156
|
+
currentVersion = currentVersion(),
|
|
157
|
+
appVersion = AppInfo.versionName(current.context),
|
|
158
|
+
packageName = current.context.packageName,
|
|
159
|
+
certSha256 = AppInfo.signingCertSha256(current.context),
|
|
160
|
+
clientSdk = current.clientSdk,
|
|
161
|
+
sdkVersion = current.sdkVersion,
|
|
162
|
+
)
|
|
163
|
+
val result = current.client.check(current.config.serverUrl, current.config.channel, identity)
|
|
164
|
+
if (result !is UpdateCheckResult.Available) return@withContext result
|
|
165
|
+
val info = result.info
|
|
166
|
+
when {
|
|
167
|
+
info.payloadType != acceptedPayload(current.clientSdk) ->
|
|
168
|
+
UpdateCheckResult.UpToDate("The latest release is not a payload this SDK can apply", "PAYLOAD_NOT_SUPPORTED")
|
|
169
|
+
current.store.isRejected(info.bundleId) ->
|
|
170
|
+
UpdateCheckResult.UpToDate("This release rolled back on this device", "ROLLED_BACK")
|
|
171
|
+
!Versions.isNewer(info.version, currentVersion()) ->
|
|
172
|
+
UpdateCheckResult.UpToDate("Already on the latest version", null)
|
|
173
|
+
else -> result
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Downloads, verifies and unpacks [info], then switches to it at [activation]. Nothing is kept when any check
|
|
179
|
+
* fails. Returns the version that will be in use.
|
|
180
|
+
*/
|
|
181
|
+
public suspend fun download(
|
|
182
|
+
info: UpdateInfo,
|
|
183
|
+
activation: Activation = Activation.NEXT_START,
|
|
184
|
+
): String =
|
|
185
|
+
withContext(Dispatchers.IO) {
|
|
186
|
+
val current = require()
|
|
187
|
+
val store = current.store
|
|
188
|
+
if (store.activeId == info.bundleId) return@withContext currentVersion()
|
|
189
|
+
val partial = store.newDownloadFile()
|
|
190
|
+
try {
|
|
191
|
+
current.client.download(info.downloadUrl, partial, current.config.maxBundleBytes)
|
|
192
|
+
if (!BundleVerifier.checksumMatches(partial, info.checksum)) {
|
|
193
|
+
throw NativeUpdateException(ErrorCodes.CHECKSUM_ERROR, "Bundle checksum does not match")
|
|
194
|
+
}
|
|
195
|
+
checkSignature(current, partial, info.signature, info.signatureAlgorithm)
|
|
196
|
+
ZipExtractor.extract(partial, store.directoryOf(info.bundleId), current.config.maxUnpackedBytes)
|
|
197
|
+
val zip = store.zipOf(info.bundleId)
|
|
198
|
+
zip.delete()
|
|
199
|
+
if (!partial.renameTo(zip)) throw NativeUpdateException(ErrorCodes.EXTRACTION_ERROR, "Bundle could not be stored")
|
|
200
|
+
store.record(info.bundleId, info.version, info.checksum.lowercase(), info.signature)
|
|
201
|
+
when (activation) {
|
|
202
|
+
Activation.NEXT_START -> store.stage(info.bundleId, current.binary)
|
|
203
|
+
Activation.NOW -> store.activate(info.bundleId, current.binary)
|
|
204
|
+
}
|
|
205
|
+
info.version
|
|
206
|
+
} catch (failure: Exception) {
|
|
207
|
+
partial.delete()
|
|
208
|
+
if (store.activeId != info.bundleId && store.stagedId != info.bundleId) store.delete(info.bundleId)
|
|
209
|
+
throw failure as? NativeUpdateException
|
|
210
|
+
?: NativeUpdateException(ErrorCodes.DOWNLOAD_ERROR, "Bundle could not be applied", failure)
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The app started cleanly on the files in use: confirms a new bundle and removes bundles that can no longer be
|
|
216
|
+
* used. Call it on every healthy start, once the first screen works.
|
|
217
|
+
*/
|
|
218
|
+
@JvmStatic
|
|
219
|
+
public fun notifyAppReady() {
|
|
220
|
+
val store = require().store
|
|
221
|
+
store.confirm()
|
|
222
|
+
store.prune()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Back to the files inside the APK; every downloaded bundle is removed. [init] may be called again after it. */
|
|
226
|
+
@JvmStatic
|
|
227
|
+
@Synchronized
|
|
228
|
+
public fun reset() {
|
|
229
|
+
state?.store?.reset()
|
|
230
|
+
state = null
|
|
231
|
+
droppedReason = null
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Java and callback-style [checkForUpdate]; [callback] runs on the main thread. */
|
|
235
|
+
@JvmStatic
|
|
236
|
+
public fun checkForUpdateAsync(callback: Callback<UpdateCheckResult>) {
|
|
237
|
+
javaScope.launch { deliver(callback) { checkForUpdate() } }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Java and callback-style [download]; [callback] runs on the main thread. */
|
|
241
|
+
@JvmStatic
|
|
242
|
+
@JvmOverloads
|
|
243
|
+
public fun downloadAsync(
|
|
244
|
+
info: UpdateInfo,
|
|
245
|
+
activation: Activation = Activation.NEXT_START,
|
|
246
|
+
callback: Callback<String>,
|
|
247
|
+
) {
|
|
248
|
+
javaScope.launch { deliver(callback) { download(info, activation) } }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Result of a callback-style call. */
|
|
252
|
+
public interface Callback<T> {
|
|
253
|
+
public fun onSuccess(value: T)
|
|
254
|
+
|
|
255
|
+
public fun onError(error: NativeUpdateException)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
private suspend fun <T> deliver(
|
|
259
|
+
callback: Callback<T>,
|
|
260
|
+
block: suspend () -> T,
|
|
261
|
+
) {
|
|
262
|
+
try {
|
|
263
|
+
val value = block()
|
|
264
|
+
mainThread.post { callback.onSuccess(value) }
|
|
265
|
+
} catch (failure: NativeUpdateException) {
|
|
266
|
+
mainThread.post { callback.onError(failure) }
|
|
267
|
+
} catch (failure: Exception) {
|
|
268
|
+
val wrapped = NativeUpdateException(ErrorCodes.NETWORK_ERROR, "Unexpected failure", failure)
|
|
269
|
+
mainThread.post { callback.onError(wrapped) }
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private fun acceptedPayload(clientSdk: String): String = if (clientSdk == "react-native") "web_bundle" else "assets"
|
|
274
|
+
|
|
275
|
+
private fun require(): State =
|
|
276
|
+
state ?: throw NativeUpdateException(ErrorCodes.NOT_INITIALIZED, "Call NativeUpdate.init() first")
|
|
277
|
+
|
|
278
|
+
/** Signatures are mandatory unless the app is debuggable AND the config turned them off. */
|
|
279
|
+
private fun checkSignature(
|
|
280
|
+
current: State,
|
|
281
|
+
zip: File,
|
|
282
|
+
signature: String?,
|
|
283
|
+
algorithm: String?,
|
|
284
|
+
) {
|
|
285
|
+
val required = current.config.requireSignature || !current.debuggable
|
|
286
|
+
if (signature.isNullOrBlank()) {
|
|
287
|
+
if (required) throw NativeUpdateException(ErrorCodes.SIGNATURE_ERROR, "Bundle signature is required")
|
|
288
|
+
return
|
|
289
|
+
}
|
|
290
|
+
if ((algorithm ?: "RSA-SHA256") != "RSA-SHA256") {
|
|
291
|
+
throw NativeUpdateException(ErrorCodes.SIGNATURE_ERROR, "Unsupported signature algorithm")
|
|
292
|
+
}
|
|
293
|
+
if (current.config.publicKey.isBlank() || !BundleVerifier.signatureValid(zip, signature, current.config.publicKey)) {
|
|
294
|
+
throw NativeUpdateException(ErrorCodes.SIGNATURE_ERROR, "Bundle signature validation failed")
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private fun verifyStored(
|
|
299
|
+
current: State,
|
|
300
|
+
id: String,
|
|
301
|
+
): Boolean {
|
|
302
|
+
val zip = current.store.zipOf(id)
|
|
303
|
+
val checksum = current.store.checksumOf(id) ?: return false
|
|
304
|
+
if (!zip.isFile || !BundleVerifier.checksumMatches(zip, checksum)) return false
|
|
305
|
+
val signature = current.store.signatureOf(id)
|
|
306
|
+
if (signature.isNullOrBlank()) return !(current.config.requireSignature || !current.debuggable)
|
|
307
|
+
return current.config.publicKey.isNotBlank() && BundleVerifier.signatureValid(zip, signature, current.config.publicKey)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Settings for [NativeUpdate.init]. Build it with [Builder]; the builder refuses an insecure or incomplete setup.
|
|
5
|
+
*
|
|
6
|
+
* ```kotlin
|
|
7
|
+
* NativeUpdateConfig.Builder(
|
|
8
|
+
* serverUrl = "https://nativeupdatebe.aoneahsan.com/api",
|
|
9
|
+
* apiKey = BuildConfig.NATIVE_UPDATE_KEY,
|
|
10
|
+
* publicKey = BuildConfig.NATIVE_UPDATE_PUBLIC_KEY,
|
|
11
|
+
* ).channel("production").build()
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
public class NativeUpdateConfig private constructor(
|
|
15
|
+
/** Canonical server base ending in `/api`. HTTPS only. */
|
|
16
|
+
public val serverUrl: String,
|
|
17
|
+
/** The app's `nu_app_…` device key. */
|
|
18
|
+
public val apiKey: String,
|
|
19
|
+
/** RSA public key (PEM or bare base64) that verifies every bundle. */
|
|
20
|
+
public val publicKey: String,
|
|
21
|
+
/** `production`, `staging` or `development`. */
|
|
22
|
+
public val channel: String,
|
|
23
|
+
/** The version of the assets shipped inside the APK; null uses the app's versionName. */
|
|
24
|
+
public val builtInVersion: String?,
|
|
25
|
+
/** Refuse a bundle without a valid signature. Only a debuggable build may turn this off. */
|
|
26
|
+
public val requireSignature: Boolean,
|
|
27
|
+
/** Largest bundle ZIP accepted, in bytes. */
|
|
28
|
+
public val maxBundleBytes: Long,
|
|
29
|
+
/** Largest unpacked size accepted, in bytes. */
|
|
30
|
+
public val maxUnpackedBytes: Long,
|
|
31
|
+
) {
|
|
32
|
+
/** Equal for two configurations that would behave the same; a repeated identical init is then a no-op. */
|
|
33
|
+
internal fun fingerprint(): String =
|
|
34
|
+
listOf(serverUrl, apiKey, publicKey, channel, builtInVersion, requireSignature, maxBundleBytes, maxUnpackedBytes)
|
|
35
|
+
.joinToString("|")
|
|
36
|
+
|
|
37
|
+
/** Fluent builder; also callable from Java. */
|
|
38
|
+
public class Builder(
|
|
39
|
+
private val serverUrl: String,
|
|
40
|
+
private val apiKey: String,
|
|
41
|
+
private val publicKey: String,
|
|
42
|
+
) {
|
|
43
|
+
private var channel = "production"
|
|
44
|
+
private var builtInVersion: String? = null
|
|
45
|
+
private var requireSignature = true
|
|
46
|
+
private var maxBundleBytes = 100L * 1024 * 1024
|
|
47
|
+
private var maxUnpackedBytes = 300L * 1024 * 1024
|
|
48
|
+
|
|
49
|
+
public fun channel(value: String): Builder = apply { channel = value }
|
|
50
|
+
|
|
51
|
+
public fun builtInVersion(value: String): Builder = apply { builtInVersion = value }
|
|
52
|
+
|
|
53
|
+
/** Unsigned bundles are accepted only when the app is debuggable; release builds always verify. */
|
|
54
|
+
public fun requireSignature(value: Boolean): Builder = apply { requireSignature = value }
|
|
55
|
+
|
|
56
|
+
public fun maxBundleBytes(value: Long): Builder = apply { maxBundleBytes = value }
|
|
57
|
+
|
|
58
|
+
public fun maxUnpackedBytes(value: Long): Builder = apply { maxUnpackedBytes = value }
|
|
59
|
+
|
|
60
|
+
public fun build(): NativeUpdateConfig {
|
|
61
|
+
fun invalid(reason: String): Nothing = throw NativeUpdateException(ErrorCodes.VALIDATION_ERROR, reason)
|
|
62
|
+
if (!serverUrl.startsWith("https://") && !isLoopbackHttp(serverUrl)) {
|
|
63
|
+
throw NativeUpdateException(ErrorCodes.INSECURE_URL, "serverUrl must use https")
|
|
64
|
+
}
|
|
65
|
+
if (!apiKey.startsWith("nu_app_")) invalid("apiKey must be the app's nu_app_ key")
|
|
66
|
+
if (requireSignature && publicKey.isBlank()) invalid("publicKey is required when signatures are required")
|
|
67
|
+
if (channel !in CHANNELS) invalid("channel must be one of ${CHANNELS.joinToString()}")
|
|
68
|
+
if (maxBundleBytes <= 0 || maxUnpackedBytes <= 0) invalid("size limits must be positive")
|
|
69
|
+
return NativeUpdateConfig(
|
|
70
|
+
serverUrl.trimEnd('/'),
|
|
71
|
+
apiKey,
|
|
72
|
+
publicKey,
|
|
73
|
+
channel,
|
|
74
|
+
builtInVersion,
|
|
75
|
+
requireSignature,
|
|
76
|
+
maxBundleBytes,
|
|
77
|
+
maxUnpackedBytes,
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
internal companion object {
|
|
83
|
+
private val CHANNELS = setOf("production", "staging", "development")
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `http://127.0.0.1` or `http://localhost`: a test server reached over `adb reverse`. Allowed only in a
|
|
87
|
+
* debuggable build ([NativeUpdate.init] refuses it otherwise); every other URL must be https.
|
|
88
|
+
*/
|
|
89
|
+
internal fun isLoopbackHttp(url: String): Boolean =
|
|
90
|
+
Regex("""^http://(127\.0\.0\.1|localhost)(:\d+)?(/.*)?$""").matches(url)
|
|
91
|
+
}
|
|
92
|
+
}
|