@shipvo/runtime 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @shipvo/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The native half of Shipvo's over-the-air updates, as an Expo module.
4
+
5
+ - Verifies every release pointer (Ed25519) and bundle (SHA-256 + size) against a public key built into the shell.
6
+ - Downloads bsdiff patches when it has the previous release, full bundles otherwise; stages atomically.
7
+ - Applies without restart, marks the release healthy when the app says so, and discards a release that fails to boot 3 times.
8
+ - Android today; on iOS and in the simulator the app runs its embedded bundle and the same live content.
9
+
10
+ ```json
11
+ { "expo": { "plugins": [["@shipvo/runtime", { "baseUrl": "https://<your control plane>", "publicKey": "<base64 Ed25519 public key>", "appId": "myshop" }]] } }
12
+ ```
13
+
14
+ ```ts
15
+ import { Runtime } from "@shipvo/runtime";
16
+ const s = Runtime.getState(); // running / pending / previous release, band, baseUrl, appId
17
+ await Runtime.checkForUpdate(true); // verify, download (patch if possible), stage, apply
18
+ Runtime.markHealthy(); // call once the first screen rendered
19
+ ```
20
+
21
+ `shipvo init` wires all of this for you.
@@ -0,0 +1,24 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = "dev.shipvo"
7
+ version = '0.0.1'
8
+
9
+ android {
10
+ namespace "dev.shipvo.runtime"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.0.1"
14
+ consumerProguardFiles "proguard-rules.pro"
15
+ }
16
+ }
17
+
18
+ dependencies {
19
+ implementation 'com.facebook.react:react-android'
20
+ // Ed25519 verification on Android 7+ (no platform Ed25519 before API 33). Pure Java, ~60 KB.
21
+ implementation 'net.i2p.crypto:eddsa:0.3.0'
22
+ // bzip2 for standard BSDIFF40 patches. 1.21 has no transitive dependencies; R8 keeps only the bzip2 reader.
23
+ implementation 'org.apache.commons:commons-compress:1.21'
24
+ }
@@ -0,0 +1,8 @@
1
+ # net.i2p eddsa references a JDK-only class in a code path Android never takes (X509 key encoding).
2
+ -dontwarn sun.security.x509.**
3
+ -keep class net.i2p.crypto.eddsa.** { *; }
4
+ -dontwarn org.apache.commons.compress.**
5
+ -dontwarn org.tukaani.xz.**
6
+ -dontwarn com.github.luben.zstd.**
7
+ -dontwarn org.brotli.dec.**
8
+ -dontwarn org.objectweb.asm.**
@@ -0,0 +1,48 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
4
+ import java.io.ByteArrayInputStream
5
+ import java.io.InputStream
6
+
7
+ /** bspatch for the standard BSDIFF40 format (Colin Percival's bsdiff 4.x): header, then bzip2 ctrl/diff/extra blocks. */
8
+ internal object Patch {
9
+ private fun offtin(b: ByteArray, o: Int): Long {
10
+ var y = (b[o + 7].toLong() and 0x7F)
11
+ for (i in 6 downTo 0) y = (y shl 8) or (b[o + i].toLong() and 0xFF)
12
+ return if ((b[o + 7].toInt() and 0x80) != 0) -y else y
13
+ }
14
+
15
+ private fun readFully(ins: InputStream, buf: ByteArray, off: Int, len: Int) {
16
+ var n = 0
17
+ while (n < len) { val r = ins.read(buf, off + n, len - n); require(r > 0) { "patch truncated" }; n += r }
18
+ }
19
+
20
+ fun apply(old: ByteArray, patch: ByteArray): ByteArray {
21
+ require(patch.size >= 32 && String(patch, 0, 8, Charsets.US_ASCII) == "BSDIFF40") { "not a BSDIFF40 patch" }
22
+ val ctrlLen = offtin(patch, 8); val diffLen = offtin(patch, 16); val newSize = offtin(patch, 24)
23
+ require(ctrlLen >= 0 && diffLen >= 0 && newSize in 0..(64L shl 20)) { "bad patch header" }
24
+ val ctrl = BZip2CompressorInputStream(ByteArrayInputStream(patch, 32, ctrlLen.toInt()))
25
+ val diff = BZip2CompressorInputStream(ByteArrayInputStream(patch, (32 + ctrlLen).toInt(), diffLen.toInt()))
26
+ val extraStart = (32 + ctrlLen + diffLen).toInt()
27
+ val extra = BZip2CompressorInputStream(ByteArrayInputStream(patch, extraStart, patch.size - extraStart))
28
+
29
+ val out = ByteArray(newSize.toInt())
30
+ var oldPos = 0L; var newPos = 0L
31
+ val c = ByteArray(24)
32
+ while (newPos < newSize) {
33
+ readFully(ctrl, c, 0, 24)
34
+ val x = offtin(c, 0); val y = offtin(c, 8); val z = offtin(c, 16)
35
+ require(x >= 0 && y >= 0 && newPos + x + y <= newSize) { "corrupt patch control" }
36
+ readFully(diff, out, newPos.toInt(), x.toInt())
37
+ for (i in 0 until x.toInt()) {
38
+ val op = oldPos + i
39
+ if (op in 0 until old.size) out[(newPos + i).toInt()] = (out[(newPos + i).toInt()] + old[op.toInt()]).toByte()
40
+ }
41
+ newPos += x; oldPos += x
42
+ readFully(extra, out, newPos.toInt(), y.toInt())
43
+ newPos += y; oldPos += z
44
+ }
45
+ ctrl.close(); diff.close(); extra.close()
46
+ return out
47
+ }
48
+ }
@@ -0,0 +1,77 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import android.content.Context
4
+ import expo.modules.core.interfaces.ReactNativeHostHandler
5
+ import java.io.File
6
+
7
+ /**
8
+ * Chooses the JS bundle at boot. Order: a staged (pending) release on trial, else the last good release,
9
+ * else the bundle embedded in the APK. A pending release that fails to reach markHealthy within 3 boots is
10
+ * discarded; a current release that boots unhealthy 3 times inside 60 s falls back to the previous one.
11
+ */
12
+ class ShipvoHostHandler(private val ctx: Context) : ReactNativeHostHandler {
13
+ override fun getJSBundleFile(useDeveloperSupport: Boolean): String? {
14
+ if (useDeveloperSupport) return null
15
+ synchronized(LOCK) {
16
+ val s = Store(ctx)
17
+ Store.bundleSelectedAt = s.now()
18
+ Store.loadsInProcess = Store.loadsInProcess + 1
19
+
20
+ val installed = s.installedBinaryVersion
21
+ if (s.binaryVersion != installed) {
22
+ val hadBundles = s.currentPath != null || s.pendingPath != null
23
+ s.resetForNewShell()
24
+ if (hadBundles) s.addEvent("shell_changed:0")
25
+ }
26
+
27
+ val pending = s.pendingPath
28
+ if (pending != null) {
29
+ if (s.trialBoots >= MAX_BOOTS || !File(pending).exists()) {
30
+ s.addEvent("crash_loop_revert:${s.pendingRelease}")
31
+ s.block(s.pendingRelease)
32
+ File(pending).delete()
33
+ s.pendingPath = null; s.pendingRelease = 0; s.trialBoots = 0
34
+ } else {
35
+ s.trialBoots = s.trialBoots + 1
36
+ Store.runningRelease = s.pendingRelease
37
+ return pending
38
+ }
39
+ }
40
+
41
+ val current = s.currentPath
42
+ if (current != null && File(current).exists()) {
43
+ val now = s.now()
44
+ if (now - s.firstUnhealthyAt > WINDOW_MS) { s.firstUnhealthyAt = now; s.unhealthyBoots = 0 }
45
+ s.unhealthyBoots = s.unhealthyBoots + 1
46
+ if (s.unhealthyBoots > MAX_BOOTS) {
47
+ s.addEvent("crash_loop_revert:${s.currentRelease}")
48
+ s.block(s.currentRelease)
49
+ revertToPrevious(s)
50
+ return selectCurrentOrEmbedded(s)
51
+ }
52
+ Store.runningRelease = s.currentRelease
53
+ return current
54
+ }
55
+ Store.runningRelease = 0
56
+ return null // embedded bundle in the APK
57
+ }
58
+ }
59
+
60
+ private fun selectCurrentOrEmbedded(s: Store): String? {
61
+ val c = s.currentPath
62
+ return if (c != null && File(c).exists()) { Store.runningRelease = s.currentRelease; c } else { Store.runningRelease = 0; null }
63
+ }
64
+
65
+ companion object {
66
+ const val MAX_BOOTS = 3
67
+ const val WINDOW_MS = 60_000L
68
+ val LOCK = Any()
69
+
70
+ internal fun revertToPrevious(s: Store) {
71
+ s.currentPath?.let { if (it != s.previousPath) File(it).delete() }
72
+ s.currentPath = s.previousPath; s.currentRelease = s.previousRelease; s.currentSha = null
73
+ s.previousPath = null; s.previousRelease = 0
74
+ s.unhealthyBoots = 0; s.firstUnhealthyAt = 0
75
+ }
76
+ }
77
+ }
@@ -0,0 +1,170 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import android.content.Context
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.os.Process
7
+ import android.os.SystemClock
8
+ import com.facebook.react.ReactApplication
9
+ import expo.modules.kotlin.exception.Exceptions
10
+ import expo.modules.kotlin.modules.Module
11
+ import expo.modules.kotlin.modules.ModuleDefinition
12
+ import org.json.JSONObject
13
+ import java.io.File
14
+ import java.net.HttpURLConnection
15
+ import java.net.URL
16
+
17
+ class ShipvoRuntimeModule : Module() {
18
+ private val ctx: Context get() = appContext.reactContext?.applicationContext ?: throw Exceptions.ReactContextLost()
19
+
20
+ override fun definition() = ModuleDefinition {
21
+ Name("ShipvoRuntime")
22
+
23
+ Function("getState") {
24
+ val s = Store(ctx)
25
+ mapOf(
26
+ "cohort" to s.cohort, "band" to s.band,
27
+ "runningRelease" to Store.runningRelease, "currentRelease" to s.currentRelease,
28
+ "pendingRelease" to s.pendingRelease, "previousRelease" to s.previousRelease,
29
+ "blockedRelease" to s.blockedRelease, "shellVersion" to s.installedBinaryVersion,
30
+ "baseUrl" to s.baseUrl, "appId" to s.appId, "shellMajor" to s.shellMajor
31
+ )
32
+ }
33
+
34
+ AsyncFunction("checkForUpdate") { apply: Boolean ->
35
+ val r = try { check() } catch (e: Exception) { mapOf("status" to "error", "error" to (e.message ?: e.javaClass.simpleName)) }
36
+ if (apply && r["status"] == "staged") reloadHost()
37
+ r
38
+ }
39
+
40
+ Function("markHealthy") {
41
+ val s = Store(ctx)
42
+ val now = SystemClock.elapsedRealtime()
43
+ val coldStart = now - Process.getStartElapsedRealtime()
44
+ val sinceLoad = if (Store.bundleSelectedAt > 0) now - Store.bundleSelectedAt else -1
45
+ var promoted = false
46
+ synchronized(ShipvoHostHandler.LOCK) {
47
+ if (s.pendingRelease != 0 && Store.runningRelease == s.pendingRelease) {
48
+ s.previousPath?.let { old -> if (old != s.currentPath) File(old).delete() }
49
+ s.previousRelease = s.currentRelease; s.previousPath = s.currentPath
50
+ s.currentRelease = s.pendingRelease; s.currentPath = s.pendingPath; s.currentSha = s.pendingSha
51
+ s.pendingRelease = 0; s.pendingPath = null; s.trialBoots = 0
52
+ s.addEvent("applied:${s.currentRelease}")
53
+ promoted = true
54
+ }
55
+ s.unhealthyBoots = 0; s.firstUnhealthyAt = 0
56
+ }
57
+ val kind = if (Store.loadsInProcess <= 1) "cold" else "reload"
58
+ mapOf("release" to Store.runningRelease, "coldStartMs" to coldStart, "sinceLoadMs" to sinceLoad, "promoted" to promoted, "kind" to kind)
59
+ }
60
+
61
+ Function("consumeEvents") { Store(ctx).consumeEvents() }
62
+
63
+ Function("rollback") {
64
+ val s = Store(ctx)
65
+ synchronized(ShipvoHostHandler.LOCK) {
66
+ s.pendingPath?.let { File(it).delete() }
67
+ s.pendingPath = null; s.pendingRelease = 0; s.trialBoots = 0
68
+ s.addEvent("rolled_back:${s.currentRelease}")
69
+ s.block(s.currentRelease)
70
+ ShipvoHostHandler.revertToPrevious(s)
71
+ }
72
+ reloadHost()
73
+ }
74
+
75
+ Function("reload") { reloadHost() }
76
+ }
77
+
78
+ private fun reloadHost() {
79
+ Handler(Looper.getMainLooper()).post {
80
+ (ctx as? ReactApplication)?.reactHost?.reload("shipvo-update")
81
+ }
82
+ }
83
+
84
+ private fun http(url: String, etag: String?): HttpURLConnection =
85
+ (URL(url).openConnection() as HttpURLConnection).apply {
86
+ connectTimeout = 10_000; readTimeout = 30_000; useCaches = false
87
+ etag?.let { setRequestProperty("If-None-Match", it) }
88
+ }
89
+
90
+ private fun resolve(s: Store, url: String) = if (url.startsWith("http")) url else "${s.baseUrl}/${url.trimStart('/')}"
91
+
92
+ private fun check(): Map<String, Any?> {
93
+ val s = Store(ctx)
94
+ require(s.baseUrl.isNotEmpty() && s.publicKey.isNotEmpty() && s.appId.isNotEmpty()) { "runtime not configured" }
95
+ val known = maxOf(s.currentRelease, s.pendingRelease, s.blockedRelease)
96
+ val conn = http("${s.baseUrl}/p/${s.appId}/${s.shellMajor}/${s.band}.json", if (known > 0) "\"$known\"" else null)
97
+ val code = conn.responseCode
98
+ if (code == 304 || code == 404) { conn.disconnect(); return mapOf("status" to "none") }
99
+ require(code == 200) { "pointer HTTP $code" }
100
+ val envelope = JSONObject(conn.inputStream.bufferedReader().use { it.readText() })
101
+ conn.disconnect()
102
+
103
+ val t0 = SystemClock.elapsedRealtime()
104
+ val bodyStr = envelope.getString("body")
105
+ require(Verify.ed25519(bodyStr.toByteArray(Charsets.UTF_8), envelope.getString("signature"), s.publicKey)) { "pointer signature invalid" }
106
+ val body = JSONObject(bodyStr)
107
+ require(body.getString("app_id") == s.appId && body.getInt("shell_major") == s.shellMajor) { "pointer for another app/shell" }
108
+ val release = body.getInt("release")
109
+ if (release <= known) return mapOf("status" to "none")
110
+ val shellVersion = ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: "0.0.0"
111
+ require(!Verify.semverLess(shellVersion, body.getString("min_shell_version"))) { "shell too old for release $release" }
112
+ val verifyPointerMs = SystemClock.elapsedRealtime() - t0
113
+
114
+ val core = body.getJSONObject("core")
115
+ val wantSha = core.getString("sha256"); val wantSize = core.getLong("size")
116
+ val tmp = File(s.dir, "dl-$release.tmp")
117
+ val d0 = SystemClock.elapsedRealtime()
118
+ var via = "full"; var bytesDownloaded = 0L; var patchError: String? = null
119
+
120
+ // 1. Try a patch against the bundle this device already has (last good release, else the APK's own bundle).
121
+ val patches = core.optJSONArray("patches")
122
+ if (patches != null && patches.length() > 0) {
123
+ try {
124
+ val baseFile = s.currentPath?.let { File(it) }?.takeIf { it.exists() }
125
+ val baseSha = if (baseFile != null) (s.currentSha ?: Verify.sha256Hex(baseFile).also { s.currentSha = it }) else s.embeddedSha()
126
+ var match: JSONObject? = null
127
+ for (i in 0 until patches.length()) { val p = patches.getJSONObject(i); if (p.getString("from_sha256") == baseSha) { match = p; break } }
128
+ if (match != null) {
129
+ val patchBytes = http(resolve(s, match.getString("url")), null).let { c ->
130
+ require(c.responseCode == 200) { "patch HTTP ${c.responseCode}" }
131
+ c.inputStream.use { it.readBytes() }.also { c.disconnect() }
132
+ }
133
+ require(patchBytes.size.toLong() == match.getLong("size") && Verify.sha256Hex(patchBytes) == match.getString("sha256")) { "patch hash mismatch" }
134
+ val base = baseFile?.readBytes() ?: s.embeddedBundle() ?: error("no base bundle")
135
+ val out = Patch.apply(base, patchBytes)
136
+ require(out.size.toLong() == wantSize && Verify.sha256Hex(out) == wantSha) { "patched bundle hash mismatch" }
137
+ tmp.writeBytes(out)
138
+ via = "patch"; bytesDownloaded = patchBytes.size.toLong()
139
+ }
140
+ } catch (e: Exception) { patchError = e.message; tmp.delete() }
141
+ }
142
+
143
+ // 2. Fall back to the full bundle.
144
+ if (via == "full") {
145
+ val dl = http(resolve(s, core.getString("url")), null)
146
+ require(dl.responseCode == 200) { "bundle HTTP ${dl.responseCode}" }
147
+ dl.inputStream.use { ins -> tmp.outputStream().use { ins.copyTo(it, 64 * 1024) } }
148
+ dl.disconnect()
149
+ bytesDownloaded = tmp.length()
150
+ }
151
+ val downloadMs = SystemClock.elapsedRealtime() - d0
152
+
153
+ val v0 = SystemClock.elapsedRealtime()
154
+ val ok = tmp.length() == wantSize && Verify.sha256Hex(tmp) == wantSha
155
+ if (!ok) { tmp.delete(); s.addEvent("verify_failed:$release"); throw IllegalStateException("bundle hash/size mismatch") }
156
+ val verifyMs = SystemClock.elapsedRealtime() - v0 + verifyPointerMs
157
+
158
+ val dest = File(s.dir, "r$release.hbc")
159
+ require(tmp.renameTo(dest)) { "could not stage bundle" }
160
+ synchronized(ShipvoHostHandler.LOCK) {
161
+ s.pendingPath?.let { if (it != dest.path) File(it).delete() }
162
+ s.pendingPath = dest.path; s.pendingRelease = release; s.trialBoots = 0; s.pendingSha = wantSha
163
+ if (s.binaryVersion == null) s.binaryVersion = s.installedBinaryVersion
164
+ s.pendingIssuedAt = body.optString("issued_at")
165
+ }
166
+ return mapOf("status" to "staged", "release" to release, "bytes" to bytesDownloaded, "via" to via, "bundleBytes" to dest.length(),
167
+ "patchError" to patchError,
168
+ "downloadMs" to downloadMs, "verifyMs" to verifyMs, "issuedAt" to body.optString("issued_at"))
169
+ }
170
+ }
@@ -0,0 +1,10 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import android.content.Context
4
+ import expo.modules.core.interfaces.Package
5
+ import expo.modules.core.interfaces.ReactNativeHostHandler
6
+
7
+ class ShipvoRuntimePackage : Package {
8
+ override fun createReactNativeHostHandlers(context: Context): List<ReactNativeHostHandler> =
9
+ listOf(ShipvoHostHandler(context))
10
+ }
@@ -0,0 +1,96 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import android.content.Context
4
+ import android.content.SharedPreferences
5
+ import android.content.pm.PackageManager
6
+ import android.os.SystemClock
7
+ import java.io.File
8
+ import kotlin.random.Random
9
+
10
+ /** Persistent runtime state. All bundle decisions go through here so the host handler and module agree. */
11
+ internal class Store(private val ctx: Context) {
12
+ private val p: SharedPreferences = ctx.getSharedPreferences("shipvo.runtime", Context.MODE_PRIVATE)
13
+ val dir: File get() = File(ctx.filesDir, "shipvo").apply { mkdirs() }
14
+
15
+ val cohort: Int
16
+ get() {
17
+ if (!p.contains("cohort")) p.edit().putInt("cohort", Random.nextInt(0, 1000)).commit()
18
+ return p.getInt("cohort", 0)
19
+ }
20
+ val band: String get() = cohort.let { if (it < 10) "b0" else if (it < 100) "b1" else "b2" }
21
+
22
+ var currentRelease: Int get() = p.getInt("current_release", 0); set(v) { p.edit().putInt("current_release", v).commit() }
23
+ var currentPath: String? get() = p.getString("current_path", null); set(v) { p.edit().putString("current_path", v).commit() }
24
+ var previousRelease: Int get() = p.getInt("previous_release", 0); set(v) { p.edit().putInt("previous_release", v).commit() }
25
+ var previousPath: String? get() = p.getString("previous_path", null); set(v) { p.edit().putString("previous_path", v).commit() }
26
+ var pendingRelease: Int get() = p.getInt("pending_release", 0); set(v) { p.edit().putInt("pending_release", v).commit() }
27
+ var pendingPath: String? get() = p.getString("pending_path", null); set(v) { p.edit().putString("pending_path", v).commit() }
28
+ var pendingIssuedAt: String? get() = p.getString("pending_issued_at", null); set(v) { p.edit().putString("pending_issued_at", v).commit() }
29
+ /** Highest release this device refused (crash-looped or rolled back). Only newer releases are fetched. */
30
+ var blockedRelease: Int get() = p.getInt("blocked_release", 0); set(v) { p.edit().putInt("blocked_release", v).commit() }
31
+ /** Shell binary the stored OTA bundles were downloaded under. */
32
+ var binaryVersion: String? get() = p.getString("binary_version", null); set(v) { p.edit().putString("binary_version", v).commit() }
33
+ fun block(release: Int) { if (release > blockedRelease) blockedRelease = release }
34
+
35
+ val installedBinaryVersion: String
36
+ get() = try {
37
+ val pi = ctx.packageManager.getPackageInfo(ctx.packageName, 0)
38
+ @Suppress("DEPRECATION") val code = if (android.os.Build.VERSION.SDK_INT >= 28) pi.longVersionCode else pi.versionCode.toLong()
39
+ "${pi.versionName}/$code"
40
+ } catch (_: Exception) { "unknown" }
41
+
42
+ /** After a shell (APK) update, bundles built for the old native code must not run. */
43
+ fun resetForNewShell() {
44
+ dir.listFiles()?.forEach { it.delete() }
45
+ p.edit().remove("current_release").remove("current_path").remove("previous_release").remove("previous_path")
46
+ .remove("pending_release").remove("pending_path").remove("pending_issued_at").remove("trial_boots")
47
+ .remove("unhealthy_boots").remove("first_unhealthy_at").remove("blocked_release")
48
+ .remove("current_sha").remove("pending_sha")
49
+ .putString("binary_version", installedBinaryVersion).commit()
50
+ }
51
+
52
+ /** sha256 of the current (last good) bundle file, cached so we don't hash 1.5 MB on every check. */
53
+ var currentSha: String? get() = p.getString("current_sha", null); set(v) { p.edit().putString("current_sha", v).commit() }
54
+ var pendingSha: String? get() = p.getString("pending_sha", null); set(v) { p.edit().putString("pending_sha", v).commit() }
55
+
56
+ /** The bundle embedded in the APK, used as the first patch baseline. */
57
+ fun embeddedBundle(): ByteArray? = try { ctx.assets.open("index.android.bundle").use { it.readBytes() } } catch (_: Exception) { null }
58
+ fun embeddedSha(): String? {
59
+ val key = "embedded_sha:" + installedBinaryVersion
60
+ p.getString(key, null)?.let { return it }
61
+ val sha = embeddedBundle()?.let { Verify.sha256Hex(it) } ?: return null
62
+ p.edit().putString(key, sha).commit(); return sha
63
+ }
64
+
65
+ var trialBoots: Int get() = p.getInt("trial_boots", 0); set(v) { p.edit().putInt("trial_boots", v).commit() }
66
+ var unhealthyBoots: Int get() = p.getInt("unhealthy_boots", 0); set(v) { p.edit().putInt("unhealthy_boots", v).commit() }
67
+ var firstUnhealthyAt: Long get() = p.getLong("first_unhealthy_at", 0); set(v) { p.edit().putLong("first_unhealthy_at", v).commit() }
68
+
69
+ fun addEvent(e: String) {
70
+ val list = p.getString("events", "")!!.split('\n').filter { it.isNotBlank() }.takeLast(49) + e
71
+ p.edit().putString("events", list.joinToString("\n")).commit()
72
+ }
73
+ fun consumeEvents(): List<String> {
74
+ val list = p.getString("events", "")!!.split('\n').filter { it.isNotBlank() }
75
+ p.edit().remove("events").commit(); return list
76
+ }
77
+
78
+ private fun meta(key: String): String? = try {
79
+ val ai = ctx.packageManager.getApplicationInfo(ctx.packageName, PackageManager.GET_META_DATA)
80
+ ai.metaData?.getString(key)
81
+ } catch (_: Exception) { null }
82
+ val baseUrl: String get() = (meta("dev.shipvo.BASE_URL") ?: "").trimEnd('/')
83
+ val publicKey: String get() = meta("dev.shipvo.PUBLIC_KEY") ?: ""
84
+ val appId: String get() = meta("dev.shipvo.APP_ID") ?: ""
85
+ val shellMajor: Int get() = (meta("dev.shipvo.SHELL_MAJOR") ?: "1").toIntOrNull() ?: 1
86
+
87
+ companion object {
88
+ /** Which release the JS that is running right now came from (set at bundle-selection time). */
89
+ @Volatile var runningRelease: Int = 0
90
+ @Volatile var bundleSelectedAt: Long = 0
91
+ /** How many times a bundle was selected in this process: 1 = cold start, more = in-process reload. */
92
+ @Volatile var loadsInProcess: Int = 0
93
+ }
94
+
95
+ fun now() = SystemClock.elapsedRealtime()
96
+ }
@@ -0,0 +1,38 @@
1
+ package dev.shipvo.runtime
2
+
3
+ import android.util.Base64
4
+ import net.i2p.crypto.eddsa.EdDSAEngine
5
+ import net.i2p.crypto.eddsa.EdDSAPublicKey
6
+ import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable
7
+ import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
8
+ import java.io.File
9
+ import java.io.FileInputStream
10
+ import java.security.MessageDigest
11
+
12
+ internal object Verify {
13
+ fun ed25519(message: ByteArray, signatureB64: String, publicKeyB64: String): Boolean = try {
14
+ val spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519)
15
+ val key = EdDSAPublicKey(EdDSAPublicKeySpec(Base64.decode(publicKeyB64, Base64.DEFAULT), spec))
16
+ val engine = EdDSAEngine(MessageDigest.getInstance(spec.hashAlgorithm))
17
+ engine.initVerify(key)
18
+ engine.update(message)
19
+ engine.verify(Base64.decode(signatureB64, Base64.DEFAULT))
20
+ } catch (_: Exception) { false }
21
+
22
+ fun sha256Hex(f: File): String {
23
+ val md = MessageDigest.getInstance("SHA-256")
24
+ FileInputStream(f).use { ins -> val buf = ByteArray(64 * 1024); while (true) { val n = ins.read(buf); if (n < 0) break; md.update(buf, 0, n) } }
25
+ return md.digest().joinToString("") { "%02x".format(it) }
26
+ }
27
+
28
+ fun sha256Hex(b: ByteArray): String =
29
+ MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
30
+
31
+ /** a < b for x.y.z */
32
+ fun semverLess(a: String, b: String): Boolean {
33
+ val pa = a.split('-')[0].split('.').map { it.toIntOrNull() ?: 0 }
34
+ val pb = b.split('-')[0].split('.').map { it.toIntOrNull() ?: 0 }
35
+ for (i in 0 until 3) { val x = pa.getOrElse(i) { 0 }; val y = pb.getOrElse(i) { 0 }; if (x != y) return x < y }
36
+ return false
37
+ }
38
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,19 @@
1
+ // Shipvo config plugin: puts the trust root and control-plane address in the native shell (AndroidManifest
2
+ // meta-data, and expo.extra.shipvo for platforms without the OTA runtime), so an over-the-air bundle can never
3
+ // change which key it is verified against.
4
+ const { withAndroidManifest, AndroidConfig } = require("expo/config-plugins");
5
+
6
+ module.exports = function withShipvo(config, props) {
7
+ const { baseUrl, publicKey, appId, shellMajor = 1 } = props || {};
8
+ if (!baseUrl || !publicKey || !appId) throw new Error("@shipvo/runtime: baseUrl, publicKey and appId are required");
9
+ config.extra = { ...(config.extra ?? {}), shipvo: { baseUrl, appId, shellMajor } };
10
+ return withAndroidManifest(config, (cfg) => {
11
+ const app = AndroidConfig.Manifest.getMainApplicationOrThrow(cfg.modResults);
12
+ const set = (name, value) => AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, name, String(value));
13
+ set("dev.shipvo.BASE_URL", baseUrl);
14
+ set("dev.shipvo.PUBLIC_KEY", publicKey);
15
+ set("dev.shipvo.APP_ID", appId);
16
+ set("dev.shipvo.SHELL_MAJOR", shellMajor);
17
+ return cfg;
18
+ });
19
+ };
@@ -0,0 +1,4 @@
1
+ {
2
+ "platforms": ["android"],
3
+ "android": { "modules": ["dev.shipvo.runtime.ShipvoRuntimeModule"] }
4
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@shipvo/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "description": "The Shipvo native runtime: a tiny Expo module that verifies (Ed25519 + SHA-256), downloads (bsdiff patches), stages and applies signed over-the-air releases, with crash-loop rollback. Plus the config plugin that pins the trust root in the native shell.",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "react-native": "./src/index.ts",
12
+ "browser": "./src/index.web.ts",
13
+ "default": "./src/index.ts"
14
+ },
15
+ "./app.plugin.js": "./app.plugin.js",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "android",
21
+ "app.plugin.js",
22
+ "expo-module.config.json",
23
+ "README.md"
24
+ ],
25
+ "peerDependencies": {
26
+ "expo": "*",
27
+ "expo-modules-core": "*",
28
+ "expo-constants": "*",
29
+ "react-native": "*"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "expo-constants": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "keywords": [
37
+ "shipvo",
38
+ "expo",
39
+ "react-native",
40
+ "ota",
41
+ "over-the-air",
42
+ "updates",
43
+ "ed25519"
44
+ ],
45
+ "homepage": "https://github.com/shipvo/shipvo#readme",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/shipvo/shipvo.git",
49
+ "directory": "packages/runtime"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "provenance": true
54
+ }
6
55
  }
package/src/index.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { requireOptionalNativeModule } from "expo-modules-core";
2
+
3
+ export type RuntimeState = {
4
+ cohort: number; band: "b0" | "b1" | "b2";
5
+ runningRelease: number; currentRelease: number; pendingRelease: number; previousRelease: number;
6
+ blockedRelease?: number; shellVersion?: string;
7
+ baseUrl: string; appId: string; shellMajor: number;
8
+ };
9
+ export type CheckResult = {
10
+ status: "none" | "staged" | "error"; release?: number; bytes?: number; downloadMs?: number; verifyMs?: number;
11
+ /** Shell 1.0.2+: "patch" when a bsdiff patch was applied, "full" otherwise. */
12
+ via?: "patch" | "full"; bundleBytes?: number; patchError?: string | null;
13
+ issuedAt?: string; error?: string;
14
+ };
15
+ export type HealthyResult = {
16
+ release: number; coldStartMs: number; sinceLoadMs: number; promoted: boolean;
17
+ /** Set by shell 1.0.1+: "cold" = first bundle load in this process, "reload" = applied without restart. */
18
+ kind?: "cold" | "reload";
19
+ };
20
+
21
+ type Native = {
22
+ getState(): RuntimeState;
23
+ checkForUpdate(apply: boolean): Promise<CheckResult>;
24
+ markHealthy(): HealthyResult;
25
+ consumeEvents(): string[];
26
+ rollback(): void;
27
+ reload(): void;
28
+ };
29
+
30
+ // The OTA runtime is Android-only for now. On iOS the app runs on its embedded bundle and live content; it still
31
+ // knows its control plane and app id from the config the plugin writes into expo.extra.shipvo.
32
+ const t0 = Date.now();
33
+ let extra: any = {};
34
+ try { extra = require("expo-constants").default?.expoConfig?.extra?.shipvo ?? {}; } catch {}
35
+ const fallback: Native = {
36
+ getState: () => ({ cohort: 0, band: "b0", runningRelease: 0, currentRelease: 0, pendingRelease: 0, previousRelease: 0,
37
+ shellVersion: "no-runtime", baseUrl: extra.baseUrl ?? "", appId: extra.appId ?? "", shellMajor: extra.shellMajor ?? 1 }),
38
+ checkForUpdate: async () => ({ status: "none" }),
39
+ markHealthy: () => ({ release: 0, coldStartMs: Date.now() - t0, sinceLoadMs: 0, promoted: false, kind: "cold" }),
40
+ consumeEvents: () => [], rollback: () => {}, reload: () => {},
41
+ };
42
+ export const Runtime: Native = requireOptionalNativeModule<Native>("ShipvoRuntime") ?? fallback;
@@ -0,0 +1,18 @@
1
+ // Simulator (web) stand-in for the native runtime: no OTA, no device. The simulator can point content at a
2
+ // control plane by setting globalThis.__PN_SIM__ = { baseUrl, appId } before the app loads.
3
+ import type { CheckResult, HealthyResult, RuntimeState } from "./index";
4
+ export type { CheckResult, HealthyResult, RuntimeState } from "./index";
5
+
6
+ const sim = (globalThis as any).__PN_SIM__ ?? {};
7
+ const t0 = Date.now();
8
+ export const Runtime = {
9
+ getState(): RuntimeState {
10
+ return { cohort: 0, band: "b0", runningRelease: 0, currentRelease: 0, pendingRelease: 0, previousRelease: 0,
11
+ shellVersion: "simulator", baseUrl: sim.baseUrl ?? "", appId: sim.appId ?? "", shellMajor: 1 };
12
+ },
13
+ async checkForUpdate(_apply: boolean): Promise<CheckResult> { return { status: "none" }; },
14
+ markHealthy(): HealthyResult { return { release: 0, coldStartMs: Date.now() - t0, sinceLoadMs: 0, promoted: false, kind: "cold" }; },
15
+ consumeEvents(): string[] { return []; },
16
+ rollback(): void {},
17
+ reload(): void { (globalThis as any).location?.reload(); },
18
+ };