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
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.os.Build
|
|
6
|
+
import androidx.activity.result.ActivityResultLauncher
|
|
7
|
+
import androidx.activity.result.IntentSenderRequest
|
|
8
|
+
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
|
|
9
|
+
import com.google.android.play.core.appupdate.AppUpdateOptions
|
|
10
|
+
import com.google.android.play.core.install.model.AppUpdateType
|
|
11
|
+
import com.google.android.play.core.install.model.UpdateAvailability
|
|
12
|
+
import com.google.android.play.core.ktx.requestAppUpdateInfo
|
|
13
|
+
import kotlinx.coroutines.CancellationException
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Google Play's in-app update, IMMEDIATE flow only: the flexible flow restarts the app the moment its download ends,
|
|
17
|
+
* which is never what a person mid-task wants.
|
|
18
|
+
*
|
|
19
|
+
* Register the launcher in the activity (`registerForActivityResult(StartIntentSenderForResult())`) and pass it here.
|
|
20
|
+
* A build not installed from Play has no Play flow: send those people to your download page instead.
|
|
21
|
+
*/
|
|
22
|
+
public object PlayAppUpdate {
|
|
23
|
+
/** What [startImmediate] did. */
|
|
24
|
+
public enum class Outcome {
|
|
25
|
+
/** Play's full-screen update is showing. */
|
|
26
|
+
STARTED,
|
|
27
|
+
|
|
28
|
+
/** Play has no newer build for this device. */
|
|
29
|
+
NOT_AVAILABLE,
|
|
30
|
+
|
|
31
|
+
/** A newer build exists but Play does not allow the immediate flow for it yet. */
|
|
32
|
+
NOT_ALLOWED,
|
|
33
|
+
|
|
34
|
+
/** This build was not installed from Google Play. */
|
|
35
|
+
NOT_PLAY_INSTALL,
|
|
36
|
+
|
|
37
|
+
/** Play could not be reached or refused the request. */
|
|
38
|
+
FAILED,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private const val PLAY_STORE = "com.android.vending"
|
|
42
|
+
|
|
43
|
+
/** True when Google Play installed the running build. */
|
|
44
|
+
@JvmStatic
|
|
45
|
+
public fun isPlayInstall(context: Context): Boolean {
|
|
46
|
+
val installer =
|
|
47
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
|
48
|
+
runCatching { context.packageManager.getInstallSourceInfo(context.packageName).installingPackageName }
|
|
49
|
+
.getOrNull()
|
|
50
|
+
} else {
|
|
51
|
+
@Suppress("DEPRECATION")
|
|
52
|
+
context.packageManager.getInstallerPackageName(context.packageName)
|
|
53
|
+
}
|
|
54
|
+
return installer == PLAY_STORE
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Starts Play's immediate update when one is available and allowed. */
|
|
58
|
+
public suspend fun startImmediate(
|
|
59
|
+
context: Context,
|
|
60
|
+
launcher: ActivityResultLauncher<IntentSenderRequest>,
|
|
61
|
+
): Outcome {
|
|
62
|
+
if (!isPlayInstall(context)) return Outcome.NOT_PLAY_INSTALL
|
|
63
|
+
return try {
|
|
64
|
+
val manager = AppUpdateManagerFactory.create(context)
|
|
65
|
+
val info = manager.requestAppUpdateInfo()
|
|
66
|
+
when {
|
|
67
|
+
info.updateAvailability() != UpdateAvailability.UPDATE_AVAILABLE -> Outcome.NOT_AVAILABLE
|
|
68
|
+
!info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) -> Outcome.NOT_ALLOWED
|
|
69
|
+
manager.startUpdateFlowForResult(info, launcher, AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build()) ->
|
|
70
|
+
Outcome.STARTED
|
|
71
|
+
else -> Outcome.FAILED
|
|
72
|
+
}
|
|
73
|
+
} catch (cancelled: CancellationException) {
|
|
74
|
+
throw cancelled
|
|
75
|
+
} catch (_: Exception) {
|
|
76
|
+
Outcome.FAILED
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The same flow for hosts that are not a ComponentActivity (Flutter's FlutterActivity, React Native's
|
|
82
|
+
* ReactActivity): Play reports back through `onActivityResult` with [requestCode].
|
|
83
|
+
*/
|
|
84
|
+
public suspend fun startImmediate(
|
|
85
|
+
activity: Activity,
|
|
86
|
+
requestCode: Int,
|
|
87
|
+
): Outcome {
|
|
88
|
+
if (!isPlayInstall(activity)) return Outcome.NOT_PLAY_INSTALL
|
|
89
|
+
return try {
|
|
90
|
+
val manager = AppUpdateManagerFactory.create(activity)
|
|
91
|
+
val info = manager.requestAppUpdateInfo()
|
|
92
|
+
when {
|
|
93
|
+
info.updateAvailability() != UpdateAvailability.UPDATE_AVAILABLE -> Outcome.NOT_AVAILABLE
|
|
94
|
+
!info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) -> Outcome.NOT_ALLOWED
|
|
95
|
+
manager.startUpdateFlowForResult(
|
|
96
|
+
info,
|
|
97
|
+
activity,
|
|
98
|
+
AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build(),
|
|
99
|
+
requestCode,
|
|
100
|
+
) -> Outcome.STARTED
|
|
101
|
+
else -> Outcome.FAILED
|
|
102
|
+
}
|
|
103
|
+
} catch (cancelled: CancellationException) {
|
|
104
|
+
throw cancelled
|
|
105
|
+
} catch (_: Exception) {
|
|
106
|
+
Outcome.FAILED
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** [resumeIfInProgress] for hosts that are not a ComponentActivity. */
|
|
111
|
+
public suspend fun resumeIfInProgress(
|
|
112
|
+
activity: Activity,
|
|
113
|
+
requestCode: Int,
|
|
114
|
+
): Boolean {
|
|
115
|
+
if (!isPlayInstall(activity)) return false
|
|
116
|
+
return try {
|
|
117
|
+
val manager = AppUpdateManagerFactory.create(activity)
|
|
118
|
+
val info = manager.requestAppUpdateInfo()
|
|
119
|
+
info.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS &&
|
|
120
|
+
manager.startUpdateFlowForResult(
|
|
121
|
+
info,
|
|
122
|
+
activity,
|
|
123
|
+
AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build(),
|
|
124
|
+
requestCode,
|
|
125
|
+
)
|
|
126
|
+
} catch (cancelled: CancellationException) {
|
|
127
|
+
throw cancelled
|
|
128
|
+
} catch (_: Exception) {
|
|
129
|
+
false
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Brings an immediate update the person left back to the front. Call it from `onResume`; Play requires it.
|
|
135
|
+
* Returns true when an update was resumed.
|
|
136
|
+
*/
|
|
137
|
+
public suspend fun resumeIfInProgress(
|
|
138
|
+
context: Context,
|
|
139
|
+
launcher: ActivityResultLauncher<IntentSenderRequest>,
|
|
140
|
+
): Boolean {
|
|
141
|
+
if (!isPlayInstall(context)) return false
|
|
142
|
+
return try {
|
|
143
|
+
val manager = AppUpdateManagerFactory.create(context)
|
|
144
|
+
val info = manager.requestAppUpdateInfo()
|
|
145
|
+
info.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS &&
|
|
146
|
+
manager.startUpdateFlowForResult(info, launcher, AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build())
|
|
147
|
+
} catch (cancelled: CancellationException) {
|
|
148
|
+
throw cancelled
|
|
149
|
+
} catch (_: Exception) {
|
|
150
|
+
false
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import com.google.android.gms.tasks.Task
|
|
5
|
+
import com.google.android.play.core.review.ReviewManagerFactory
|
|
6
|
+
import kotlinx.coroutines.CancellationException
|
|
7
|
+
import kotlinx.coroutines.suspendCancellableCoroutine
|
|
8
|
+
import kotlin.coroutines.resume
|
|
9
|
+
import kotlin.coroutines.resumeWithException
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Google Play's in-app review sheet. Ask right after something went well for the person, never on launch.
|
|
13
|
+
*
|
|
14
|
+
* Play decides whether the sheet actually appears and never says, so [request] reports only whether Play accepted
|
|
15
|
+
* the request. Pair it with [shouldAsk] to keep the asking rare.
|
|
16
|
+
*/
|
|
17
|
+
public object PlayReview {
|
|
18
|
+
/** What [request] did. */
|
|
19
|
+
public enum class Outcome {
|
|
20
|
+
/** Play accepted the request; it may or may not have shown the sheet. */
|
|
21
|
+
REQUESTED,
|
|
22
|
+
|
|
23
|
+
/** This build was not installed from Google Play, so there is no Play sheet. */
|
|
24
|
+
NOT_PLAY_INSTALL,
|
|
25
|
+
|
|
26
|
+
/** Play refused or could not be reached. */
|
|
27
|
+
FAILED,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private const val MS_PER_DAY = 86_400_000L
|
|
31
|
+
|
|
32
|
+
/** Asks Play for its review sheet. */
|
|
33
|
+
public suspend fun request(activity: Activity): Outcome {
|
|
34
|
+
if (!PlayAppUpdate.isPlayInstall(activity)) return Outcome.NOT_PLAY_INSTALL
|
|
35
|
+
return try {
|
|
36
|
+
val manager = ReviewManagerFactory.create(activity)
|
|
37
|
+
val info = manager.requestReviewFlow().finished()
|
|
38
|
+
manager.launchReviewFlow(activity, info).finished()
|
|
39
|
+
Outcome.REQUESTED
|
|
40
|
+
} catch (cancelled: CancellationException) {
|
|
41
|
+
throw cancelled
|
|
42
|
+
} catch (_: Exception) {
|
|
43
|
+
Outcome.FAILED
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* True when the app should ask now: after at least [minSuccesses] good moments, and never twice within
|
|
49
|
+
* [minDaysBetween] days. [lastAskedMs] is 0 when it never asked. The app stores both numbers.
|
|
50
|
+
*/
|
|
51
|
+
@JvmStatic
|
|
52
|
+
@JvmOverloads
|
|
53
|
+
public fun shouldAsk(
|
|
54
|
+
successes: Int,
|
|
55
|
+
lastAskedMs: Long,
|
|
56
|
+
nowMs: Long,
|
|
57
|
+
minSuccesses: Int = 3,
|
|
58
|
+
minDaysBetween: Long = 90,
|
|
59
|
+
): Boolean = successes >= minSuccesses && (lastAskedMs == 0L || nowMs - lastAskedMs >= minDaysBetween * MS_PER_DAY)
|
|
60
|
+
|
|
61
|
+
private suspend fun <T> Task<T>.finished(): T =
|
|
62
|
+
suspendCancellableCoroutine { continuation ->
|
|
63
|
+
addOnCompleteListener { task ->
|
|
64
|
+
val failure = task.exception
|
|
65
|
+
if (failure == null) continuation.resume(task.result) else continuation.resumeWithException(failure)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android
|
|
2
|
+
|
|
3
|
+
/** One available bundle, as the server described it. */
|
|
4
|
+
public data class UpdateInfo(
|
|
5
|
+
public val version: String,
|
|
6
|
+
public val bundleId: String,
|
|
7
|
+
public val downloadUrl: String,
|
|
8
|
+
public val checksum: String,
|
|
9
|
+
public val signature: String?,
|
|
10
|
+
public val signatureAlgorithm: String?,
|
|
11
|
+
public val payloadType: String,
|
|
12
|
+
public val size: Long,
|
|
13
|
+
public val mandatory: Boolean,
|
|
14
|
+
public val releaseNotes: String?,
|
|
15
|
+
public val minNativeVersion: String?,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
/** The answer to [NativeUpdate.checkForUpdate]. */
|
|
19
|
+
public sealed class UpdateCheckResult {
|
|
20
|
+
/** Nothing newer for this device. [code] is set for a reason the app may care about. */
|
|
21
|
+
public data class UpToDate(
|
|
22
|
+
public val message: String?,
|
|
23
|
+
public val code: String?,
|
|
24
|
+
) : UpdateCheckResult()
|
|
25
|
+
|
|
26
|
+
/** A newer bundle this SDK can apply. */
|
|
27
|
+
public data class Available(
|
|
28
|
+
public val info: UpdateInfo,
|
|
29
|
+
) : UpdateCheckResult()
|
|
30
|
+
|
|
31
|
+
/** A newer bundle needs a newer app binary first ([minNativeVersion]). */
|
|
32
|
+
public data class NativeUpdateRequired(
|
|
33
|
+
public val minNativeVersion: String,
|
|
34
|
+
) : UpdateCheckResult()
|
|
35
|
+
|
|
36
|
+
/** A newer release exists, but delivery is paused for the developer's account. */
|
|
37
|
+
public data class Held(
|
|
38
|
+
public val version: String?,
|
|
39
|
+
public val message: String?,
|
|
40
|
+
) : UpdateCheckResult()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** When a downloaded bundle replaces the running one. */
|
|
44
|
+
public enum class Activation {
|
|
45
|
+
/** At the next cold start: files never change under a running screen. The default. */
|
|
46
|
+
NEXT_START,
|
|
47
|
+
|
|
48
|
+
/** Now: the next [NativeUpdate.file] read returns the new files. */
|
|
49
|
+
NOW,
|
|
50
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android.internal
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.content.pm.ApplicationInfo
|
|
5
|
+
import android.content.pm.PackageManager
|
|
6
|
+
import android.os.Build
|
|
7
|
+
import java.security.MessageDigest
|
|
8
|
+
|
|
9
|
+
/** Facts about the running app binary, read from the package manager. */
|
|
10
|
+
internal object AppInfo {
|
|
11
|
+
fun versionName(context: Context): String? =
|
|
12
|
+
runCatching { packageInfo(context, 0).versionName }.getOrNull()
|
|
13
|
+
|
|
14
|
+
/** `versionCode:versionName`; changes on every store or sideload update, which retires older OTA bundles. */
|
|
15
|
+
fun binaryIdentity(context: Context): String =
|
|
16
|
+
runCatching {
|
|
17
|
+
val info = packageInfo(context, 0)
|
|
18
|
+
val code = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) info.longVersionCode else legacyCode(info)
|
|
19
|
+
"$code:${info.versionName}"
|
|
20
|
+
}.getOrDefault("unknown")
|
|
21
|
+
|
|
22
|
+
fun isDebuggable(context: Context): Boolean = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
|
|
23
|
+
|
|
24
|
+
/** SHA-256 of the first signing certificate, lowercase hex, for per-key client restrictions. */
|
|
25
|
+
fun signingCertSha256(context: Context): String? =
|
|
26
|
+
runCatching {
|
|
27
|
+
val signatures =
|
|
28
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
|
29
|
+
val info = packageInfo(context, PackageManager.GET_SIGNING_CERTIFICATES).signingInfo
|
|
30
|
+
if (info?.hasMultipleSigners() == true) info.apkContentsSigners else info?.signingCertificateHistory
|
|
31
|
+
} else {
|
|
32
|
+
legacySignatures(context)
|
|
33
|
+
}
|
|
34
|
+
val first = signatures?.firstOrNull() ?: return null
|
|
35
|
+
MessageDigest.getInstance("SHA-256").digest(first.toByteArray()).joinToString("") {
|
|
36
|
+
"%02x".format(it.toInt() and 0xff)
|
|
37
|
+
}
|
|
38
|
+
}.getOrNull()
|
|
39
|
+
|
|
40
|
+
private fun packageInfo(
|
|
41
|
+
context: Context,
|
|
42
|
+
flags: Int,
|
|
43
|
+
) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
44
|
+
context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(flags.toLong()))
|
|
45
|
+
} else {
|
|
46
|
+
@Suppress("DEPRECATION")
|
|
47
|
+
context.packageManager.getPackageInfo(context.packageName, flags)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
@Suppress("DEPRECATION")
|
|
51
|
+
private fun legacyCode(info: android.content.pm.PackageInfo): Long = info.versionCode.toLong()
|
|
52
|
+
|
|
53
|
+
@Suppress("DEPRECATION")
|
|
54
|
+
private fun legacySignatures(context: Context) =
|
|
55
|
+
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures
|
|
56
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android.internal
|
|
2
|
+
|
|
3
|
+
import android.annotation.SuppressLint
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.SharedPreferences
|
|
6
|
+
import java.io.File
|
|
7
|
+
import java.util.UUID
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Where bundles live and which one is in use (docs/protocol/CLIENT-PROTOCOL.md §3).
|
|
11
|
+
*
|
|
12
|
+
* Layout: `filesDir/native-update-sdk/bundles/<bundleId>/` holds the unpacked files and `<bundleId>.zip` the verified
|
|
13
|
+
* ZIP, kept so every cold start can re-check its checksum and signature. State is in SharedPreferences and written
|
|
14
|
+
* with `commit()`, so a crash right after an activation cannot lose it.
|
|
15
|
+
*
|
|
16
|
+
* Lint: `ApplySharedPref` is deliberate (`commit()` is the durability guarantee above); `UseKtx` would add core-ktx to
|
|
17
|
+
* every host app for a one-line helper.
|
|
18
|
+
*/
|
|
19
|
+
@SuppressLint("ApplySharedPref", "UseKtx")
|
|
20
|
+
internal class BundleStore(
|
|
21
|
+
context: Context,
|
|
22
|
+
) {
|
|
23
|
+
private val prefs: SharedPreferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
24
|
+
private val bundlesDir = File(context.filesDir, "native-update-sdk/bundles")
|
|
25
|
+
|
|
26
|
+
val deviceId: String
|
|
27
|
+
get() =
|
|
28
|
+
prefs.getString(KEY_DEVICE_ID, null) ?: UUID.randomUUID().toString().also {
|
|
29
|
+
prefs.edit().putString(KEY_DEVICE_ID, it).commit()
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
val activeId: String? get() = prefs.getString(KEY_ACTIVE, null)
|
|
33
|
+
val pendingId: String? get() = prefs.getString(KEY_PENDING, null)
|
|
34
|
+
val stagedId: String? get() = prefs.getString(KEY_STAGED, null)
|
|
35
|
+
|
|
36
|
+
fun versionOf(id: String): String? = prefs.getString(KEY_VERSION + id, null)
|
|
37
|
+
|
|
38
|
+
fun checksumOf(id: String): String? = prefs.getString(KEY_CHECKSUM + id, null)
|
|
39
|
+
|
|
40
|
+
fun signatureOf(id: String): String? = prefs.getString(KEY_SIGNATURE + id, null)
|
|
41
|
+
|
|
42
|
+
fun directoryOf(id: String): File = File(bundlesDir, id)
|
|
43
|
+
|
|
44
|
+
fun zipOf(id: String): File = File(bundlesDir, "$id.zip")
|
|
45
|
+
|
|
46
|
+
fun newDownloadFile(): File {
|
|
47
|
+
bundlesDir.mkdirs()
|
|
48
|
+
return File.createTempFile("download-", ".part", bundlesDir)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** True when this bundle rolled back on this device; it is never offered again here. */
|
|
52
|
+
fun isRejected(id: String): Boolean = id in (prefs.getStringSet(KEY_REJECTED, emptySet()) ?: emptySet())
|
|
53
|
+
|
|
54
|
+
/** Remembers a verified, unpacked bundle. */
|
|
55
|
+
fun record(
|
|
56
|
+
id: String,
|
|
57
|
+
version: String,
|
|
58
|
+
checksum: String,
|
|
59
|
+
signature: String?,
|
|
60
|
+
) {
|
|
61
|
+
prefs.edit()
|
|
62
|
+
.putString(KEY_VERSION + id, version)
|
|
63
|
+
.putString(KEY_CHECKSUM + id, checksum)
|
|
64
|
+
.apply { if (signature != null) putString(KEY_SIGNATURE + id, signature) else remove(KEY_SIGNATURE + id) }
|
|
65
|
+
.commit()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Makes [id] the bundle used from the next cold start of this same binary. */
|
|
69
|
+
fun stage(
|
|
70
|
+
id: String,
|
|
71
|
+
binary: String,
|
|
72
|
+
) {
|
|
73
|
+
prefs.edit().putString(KEY_STAGED, id).putString(KEY_BINARY, binary).commit()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Makes [id] active now: the old active becomes the rollback target and [id] waits for its first healthy start. */
|
|
77
|
+
fun activate(
|
|
78
|
+
id: String,
|
|
79
|
+
binary: String,
|
|
80
|
+
) {
|
|
81
|
+
val current = activeId
|
|
82
|
+
prefs.edit()
|
|
83
|
+
.putString(KEY_ACTIVE, id)
|
|
84
|
+
.apply { if (current != null && current != id) putString(KEY_PREVIOUS, current) }
|
|
85
|
+
.putString(KEY_PENDING, id)
|
|
86
|
+
.putInt(KEY_ATTEMPTS, 0)
|
|
87
|
+
.putString(KEY_BINARY, binary)
|
|
88
|
+
.remove(KEY_STAGED)
|
|
89
|
+
.commit()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Runs once per process before anything reads a file. Returns why a bundle was dropped, or null.
|
|
94
|
+
*
|
|
95
|
+
* Order: retire bundles from an older binary, switch to a staged bundle, count an unconfirmed start (the third
|
|
96
|
+
* rolls back), then re-check the active bundle's checksum and signature.
|
|
97
|
+
*/
|
|
98
|
+
fun onColdStart(
|
|
99
|
+
binary: String,
|
|
100
|
+
verify: (id: String) -> Boolean,
|
|
101
|
+
): String? {
|
|
102
|
+
val recordedBinary = prefs.getString(KEY_BINARY, null)
|
|
103
|
+
if ((activeId != null || stagedId != null) && recordedBinary != null && recordedBinary != binary) {
|
|
104
|
+
clearState()
|
|
105
|
+
deleteAllBundles()
|
|
106
|
+
return "the app binary changed"
|
|
107
|
+
}
|
|
108
|
+
stagedId?.let { staged ->
|
|
109
|
+
if (directoryOf(staged).isDirectory) activate(staged, binary) else prefs.edit().remove(KEY_STAGED).commit()
|
|
110
|
+
}
|
|
111
|
+
pendingId?.let { pending ->
|
|
112
|
+
val attempt = prefs.getInt(KEY_ATTEMPTS, 0) + 1
|
|
113
|
+
if (attempt > MAX_UNCONFIRMED_STARTS) {
|
|
114
|
+
rollback(pending)
|
|
115
|
+
return "it did not confirm a healthy start"
|
|
116
|
+
}
|
|
117
|
+
prefs.edit().putInt(KEY_ATTEMPTS, attempt).commit()
|
|
118
|
+
}
|
|
119
|
+
val active = activeId ?: return null
|
|
120
|
+
if (!directoryOf(active).isDirectory || !verify(active)) {
|
|
121
|
+
rollback(active)
|
|
122
|
+
return "its files failed verification"
|
|
123
|
+
}
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The app started cleanly on the active bundle. */
|
|
128
|
+
fun confirm() {
|
|
129
|
+
prefs.edit().remove(KEY_PENDING).remove(KEY_ATTEMPTS).commit()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Back to the previous bundle, or to the files inside the APK when there is none. [failed] is never reused. */
|
|
133
|
+
fun rollback(failed: String) {
|
|
134
|
+
val previous = prefs.getString(KEY_PREVIOUS, null)?.takeIf { it != failed && directoryOf(it).isDirectory }
|
|
135
|
+
val rejected = (prefs.getStringSet(KEY_REJECTED, emptySet()) ?: emptySet()) + failed
|
|
136
|
+
prefs.edit()
|
|
137
|
+
.apply { if (previous != null) putString(KEY_ACTIVE, previous) else remove(KEY_ACTIVE) }
|
|
138
|
+
.remove(KEY_PREVIOUS)
|
|
139
|
+
.remove(KEY_PENDING)
|
|
140
|
+
.remove(KEY_ATTEMPTS)
|
|
141
|
+
.apply { if (stagedId == failed) remove(KEY_STAGED) }
|
|
142
|
+
.putStringSet(KEY_REJECTED, rejected.toList().takeLast(MAX_REJECTED).toSet())
|
|
143
|
+
.commit()
|
|
144
|
+
delete(failed)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Keeps the active, rollback, pending and staged bundles; deletes every other bundle and stray download. */
|
|
148
|
+
fun prune() {
|
|
149
|
+
val keep = setOfNotNull(activeId, prefs.getString(KEY_PREVIOUS, null), pendingId, stagedId)
|
|
150
|
+
bundlesDir.listFiles()?.forEach { file ->
|
|
151
|
+
val id = file.name.removeSuffix(".zip")
|
|
152
|
+
val stray = file.name.endsWith(".part")
|
|
153
|
+
if (stray || id !in keep) {
|
|
154
|
+
file.deleteRecursively()
|
|
155
|
+
if (!stray && !file.name.endsWith(".zip")) forget(id)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Back to the files inside the APK, everything downloaded removed. The device id is kept. */
|
|
161
|
+
fun reset() {
|
|
162
|
+
clearState()
|
|
163
|
+
deleteAllBundles()
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
fun delete(id: String) {
|
|
167
|
+
directoryOf(id).deleteRecursively()
|
|
168
|
+
zipOf(id).delete()
|
|
169
|
+
forget(id)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private fun forget(id: String) {
|
|
173
|
+
prefs.edit().remove(KEY_VERSION + id).remove(KEY_CHECKSUM + id).remove(KEY_SIGNATURE + id).commit()
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private fun clearState() {
|
|
177
|
+
prefs.edit()
|
|
178
|
+
.remove(KEY_ACTIVE)
|
|
179
|
+
.remove(KEY_PREVIOUS)
|
|
180
|
+
.remove(KEY_PENDING)
|
|
181
|
+
.remove(KEY_ATTEMPTS)
|
|
182
|
+
.remove(KEY_STAGED)
|
|
183
|
+
.remove(KEY_BINARY)
|
|
184
|
+
.commit()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private fun deleteAllBundles() {
|
|
188
|
+
bundlesDir.listFiles()?.forEach { file ->
|
|
189
|
+
forget(file.name.removeSuffix(".zip"))
|
|
190
|
+
file.deleteRecursively()
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private companion object {
|
|
195
|
+
const val PREFS = "native_update_sdk"
|
|
196
|
+
const val KEY_DEVICE_ID = "device_id"
|
|
197
|
+
const val KEY_ACTIVE = "active"
|
|
198
|
+
const val KEY_PREVIOUS = "previous"
|
|
199
|
+
const val KEY_PENDING = "pending"
|
|
200
|
+
const val KEY_ATTEMPTS = "pending_attempts"
|
|
201
|
+
const val KEY_STAGED = "staged"
|
|
202
|
+
const val KEY_BINARY = "active_binary"
|
|
203
|
+
const val KEY_REJECTED = "rejected"
|
|
204
|
+
const val KEY_VERSION = "version:"
|
|
205
|
+
const val KEY_CHECKSUM = "checksum:"
|
|
206
|
+
const val KEY_SIGNATURE = "signature:"
|
|
207
|
+
const val MAX_UNCONFIRMED_STARTS = 2
|
|
208
|
+
const val MAX_REJECTED = 20
|
|
209
|
+
}
|
|
210
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
package com.aoneahsan.nativeupdate.android.internal
|
|
2
|
+
|
|
3
|
+
import java.io.File
|
|
4
|
+
import java.security.KeyFactory
|
|
5
|
+
import java.security.MessageDigest
|
|
6
|
+
import java.security.Signature
|
|
7
|
+
import java.security.spec.X509EncodedKeySpec
|
|
8
|
+
import java.util.Base64
|
|
9
|
+
|
|
10
|
+
/** SHA-256 and RSA-SHA256 checks over the exact ZIP bytes (docs/protocol/CLIENT-PROTOCOL.md §2). */
|
|
11
|
+
internal object BundleVerifier {
|
|
12
|
+
/** Lowercase hex SHA-256 of the file, streamed. */
|
|
13
|
+
fun sha256Hex(file: File): String {
|
|
14
|
+
val digest = MessageDigest.getInstance("SHA-256")
|
|
15
|
+
file.inputStream().use { input ->
|
|
16
|
+
val buffer = ByteArray(BUFFER)
|
|
17
|
+
while (true) {
|
|
18
|
+
val read = input.read(buffer)
|
|
19
|
+
if (read < 0) break
|
|
20
|
+
digest.update(buffer, 0, read)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** True when [expected] (any case) equals the file's SHA-256. */
|
|
27
|
+
fun checksumMatches(
|
|
28
|
+
file: File,
|
|
29
|
+
expected: String,
|
|
30
|
+
): Boolean = expected.isNotBlank() && sha256Hex(file).equals(expected.trim(), ignoreCase = true)
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Verifies a base64 `SHA256withRSA` (PKCS#1 v1.5) signature of the file with an X.509 public key, given as PEM
|
|
34
|
+
* or bare base64. Any malformed input is a failed verification, never an exception.
|
|
35
|
+
*/
|
|
36
|
+
fun signatureValid(
|
|
37
|
+
file: File,
|
|
38
|
+
signatureBase64: String,
|
|
39
|
+
publicKey: String,
|
|
40
|
+
): Boolean =
|
|
41
|
+
try {
|
|
42
|
+
val keyBytes =
|
|
43
|
+
Base64.getMimeDecoder().decode(
|
|
44
|
+
publicKey
|
|
45
|
+
.replace("-----BEGIN PUBLIC KEY-----", "")
|
|
46
|
+
.replace("-----END PUBLIC KEY-----", "")
|
|
47
|
+
.replace(Regex("\\s"), ""),
|
|
48
|
+
)
|
|
49
|
+
val key = KeyFactory.getInstance("RSA").generatePublic(X509EncodedKeySpec(keyBytes))
|
|
50
|
+
val verifier = Signature.getInstance("SHA256withRSA")
|
|
51
|
+
verifier.initVerify(key)
|
|
52
|
+
file.inputStream().use { input ->
|
|
53
|
+
val buffer = ByteArray(BUFFER)
|
|
54
|
+
while (true) {
|
|
55
|
+
val read = input.read(buffer)
|
|
56
|
+
if (read < 0) break
|
|
57
|
+
verifier.update(buffer, 0, read)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
verifier.verify(Base64.getMimeDecoder().decode(signatureBase64.trim()))
|
|
61
|
+
} catch (_: Exception) {
|
|
62
|
+
false
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private const val BUFFER = 64 * 1024
|
|
66
|
+
}
|