@shipvo/runtime 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 and iOS. iOS downloads full bundles (patches are Android-only for now) and is verified on the iOS Simulator in CI; in the web simulator the app runs the same release as the web build.
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,26 @@
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, withInfoPlist, 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
+ config = withInfoPlist(config, (cfg) => {
11
+ cfg.modResults.ShipvoBaseURL = baseUrl;
12
+ cfg.modResults.ShipvoPublicKey = publicKey;
13
+ cfg.modResults.ShipvoAppId = appId;
14
+ cfg.modResults.ShipvoShellMajor = String(shellMajor);
15
+ return cfg;
16
+ });
17
+ return withAndroidManifest(config, (cfg) => {
18
+ const app = AndroidConfig.Manifest.getMainApplicationOrThrow(cfg.modResults);
19
+ const set = (name, value) => AndroidConfig.Manifest.addMetaDataItemToMainApplication(app, name, String(value));
20
+ set("dev.shipvo.BASE_URL", baseUrl);
21
+ set("dev.shipvo.PUBLIC_KEY", publicKey);
22
+ set("dev.shipvo.APP_ID", appId);
23
+ set("dev.shipvo.SHELL_MAJOR", shellMajor);
24
+ return cfg;
25
+ });
26
+ };
@@ -0,0 +1,19 @@
1
+ {
2
+ "platforms": [
3
+ "android",
4
+ "apple"
5
+ ],
6
+ "android": {
7
+ "modules": [
8
+ "dev.shipvo.runtime.ShipvoRuntimeModule"
9
+ ]
10
+ },
11
+ "apple": {
12
+ "modules": [
13
+ "ShipvoRuntimeModule"
14
+ ],
15
+ "reactDelegateHandlers": [
16
+ "ShipvoReactDelegateHandler"
17
+ ]
18
+ }
19
+ }
@@ -0,0 +1,92 @@
1
+ import Foundation
2
+
3
+ /// The bundle-choice rules. Kept free of Expo and React imports so they run under `swift test` on a plain Mac.
4
+ enum ShipvoBundleSelector {
5
+ static let maxBoots = 3
6
+ static let windowSeconds: TimeInterval = 60
7
+
8
+ /// Idempotent per load: React Native asks for the URL more than once, and only the first ask counts as a boot.
9
+ static func select(_ s: Store) -> URL? {
10
+ Store.lock.lock(); defer { Store.lock.unlock() }
11
+ if Store.selection.set { return Store.selection.url }
12
+ let url = choose(s)
13
+ Store.selection = (url, true)
14
+ return url
15
+ }
16
+
17
+ /// The app reports a healthy start: a pending release that is the one running becomes current. Returns whether it was promoted.
18
+ @discardableResult
19
+ static func promoteIfRunning(_ s: Store) -> Bool {
20
+ Store.lock.lock(); defer { Store.lock.unlock() }
21
+ var promoted = false
22
+ if s.pendingRelease != 0 && Store.runningRelease == s.pendingRelease {
23
+ if let old = s.previousPath, old != s.currentPath { remove(old) }
24
+ s.previousRelease = s.currentRelease; s.previousPath = s.currentPath
25
+ s.currentRelease = s.pendingRelease; s.currentPath = s.pendingPath; s.currentSha = s.pendingSha
26
+ s.pendingRelease = 0; s.pendingPath = nil; s.trialBoots = 0
27
+ s.addEvent("applied:\(s.currentRelease)")
28
+ promoted = true
29
+ }
30
+ s.unhealthyBoots = 0; s.firstUnhealthyAt = 0
31
+ return promoted
32
+ }
33
+
34
+ /// Called before a reload so the next ask is a fresh load.
35
+ static func invalidate() { Store.lock.lock(); Store.selection = (nil, false); Store.lock.unlock() }
36
+
37
+ private static func exists(_ path: String?) -> Bool { path != nil && FileManager.default.fileExists(atPath: path!) }
38
+ private static func remove(_ path: String?) { if let p = path { try? FileManager.default.removeItem(atPath: p) } }
39
+
40
+ private static func choose(_ s: Store) -> URL? {
41
+ Store.bundleSelectedAt = Store.now()
42
+ Store.loadsInProcess += 1
43
+
44
+ let installed = s.installedBinaryVersion
45
+ if s.binaryVersion != installed {
46
+ let hadBundles = s.currentPath != nil || s.pendingPath != nil
47
+ s.resetForNewShell()
48
+ if hadBundles { s.addEvent("shell_changed:0") }
49
+ }
50
+
51
+ if let pending = s.pendingPath {
52
+ if s.trialBoots >= maxBoots || !exists(pending) {
53
+ s.addEvent("crash_loop_revert:\(s.pendingRelease)")
54
+ s.block(s.pendingRelease)
55
+ remove(pending)
56
+ s.pendingPath = nil; s.pendingRelease = 0; s.trialBoots = 0
57
+ } else {
58
+ s.trialBoots += 1
59
+ Store.runningRelease = s.pendingRelease
60
+ return URL(fileURLWithPath: pending)
61
+ }
62
+ }
63
+
64
+ if exists(s.currentPath) {
65
+ let now = Store.now()
66
+ if now - s.firstUnhealthyAt > windowSeconds { s.firstUnhealthyAt = now; s.unhealthyBoots = 0 }
67
+ s.unhealthyBoots += 1
68
+ if s.unhealthyBoots > maxBoots {
69
+ s.addEvent("crash_loop_revert:\(s.currentRelease)")
70
+ s.block(s.currentRelease)
71
+ revertToPrevious(s)
72
+ return currentOrEmbedded(s)
73
+ }
74
+ Store.runningRelease = s.currentRelease
75
+ return URL(fileURLWithPath: s.currentPath!)
76
+ }
77
+ Store.runningRelease = 0
78
+ return nil // the embedded bundle
79
+ }
80
+
81
+ private static func currentOrEmbedded(_ s: Store) -> URL? {
82
+ if exists(s.currentPath) { Store.runningRelease = s.currentRelease; return URL(fileURLWithPath: s.currentPath!) }
83
+ Store.runningRelease = 0; return nil
84
+ }
85
+
86
+ static func revertToPrevious(_ s: Store) {
87
+ if let c = s.currentPath, c != s.previousPath { remove(c) }
88
+ s.currentPath = s.previousPath; s.currentRelease = s.previousRelease; s.currentSha = nil
89
+ s.previousPath = nil; s.previousRelease = 0
90
+ s.unhealthyBoots = 0; s.firstUnhealthyAt = 0
91
+ }
92
+ }
@@ -0,0 +1,16 @@
1
+ import ExpoModulesCore
2
+ import Foundation
3
+
4
+ /// Chooses the JS bundle at load. Order: a staged (pending) release on trial, else the last good release, else the
5
+ /// bundle embedded in the app (returning nil lets React Native use main.jsbundle). A pending release that does not
6
+ /// reach markHealthy within 3 loads is discarded; a current release that loads unhealthy 3 times inside 60 s falls
7
+ /// back to the previous one. Same rules as the Android host handler.
8
+ public final class ShipvoReactDelegateHandler: ExpoReactDelegateHandler {
9
+ public override func bundleURL(reactDelegate: ExpoReactDelegate) -> URL? {
10
+ #if DEBUG
11
+ return nil // development builds load from Metro
12
+ #else
13
+ return ShipvoBundleSelector.select(Store())
14
+ #endif
15
+ }
16
+ }
@@ -0,0 +1,25 @@
1
+ require 'json'
2
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
3
+
4
+ Pod::Spec.new do |s|
5
+ s.name = 'ShipvoRuntime'
6
+ s.version = package['version']
7
+ s.summary = package['description']
8
+ s.description = package['description']
9
+ s.license = package['license']
10
+ s.author = 'Shipvo'
11
+ s.homepage = 'https://shipvo.dev'
12
+ s.platforms = { :ios => '16.4' }
13
+ s.swift_version = '5.9'
14
+ s.source = { git: 'https://github.com/shipvo/shipvo.git' }
15
+ s.static_framework = true
16
+
17
+ s.dependency 'ExpoModulesCore'
18
+ s.dependency 'React-Core'
19
+
20
+ s.pod_target_xcconfig = {
21
+ 'DEFINES_MODULE' => 'YES',
22
+ 'SWIFT_COMPILATION_MODE' => 'wholemodule'
23
+ }
24
+ s.source_files = '**/*.{h,m,swift}'
25
+ end
@@ -0,0 +1,72 @@
1
+ import ExpoModulesCore
2
+ import Foundation
3
+ import React
4
+
5
+ /// JS-facing runtime: getState / checkForUpdate / markHealthy / consumeEvents / rollback / reload.
6
+ /// Same contract as the Android module so `Runtime` in src/index.ts is platform-neutral.
7
+ public final class ShipvoRuntimeModule: Module {
8
+ public func definition() -> ModuleDefinition {
9
+ Name("ShipvoRuntime")
10
+
11
+ Function("getState") { () -> [String: Any] in
12
+ let s = Store()
13
+ var out: [String: Any] = [
14
+ "cohort": s.cohort, "band": s.band,
15
+ "runningRelease": Store.runningRelease, "currentRelease": s.currentRelease,
16
+ "pendingRelease": s.pendingRelease, "previousRelease": s.previousRelease,
17
+ "shellVersion": s.installedBinaryVersion,
18
+ "baseUrl": s.baseUrl, "appId": s.appId, "shellMajor": s.shellMajor,
19
+ ]
20
+ if s.blockedRelease != 0 { out["blockedRelease"] = s.blockedRelease }
21
+ return out
22
+ }
23
+
24
+ AsyncFunction("checkForUpdate") { (apply: Bool) async -> [String: Any] in
25
+ let r: [String: Any]
26
+ do { r = try await Updater.check(Store()) }
27
+ catch { r = ["status": "error", "error": (error as? UpdateError)?.message ?? error.localizedDescription] }
28
+ if apply, r["status"] as? String == "staged" { Self.reloadHost() }
29
+ return r
30
+ }
31
+
32
+ Function("markHealthy") { () -> [String: Any] in
33
+ let s = Store()
34
+ let now = Store.now()
35
+ let coldStart = max(0, (Date().timeIntervalSince1970 - Self.processStart()) * 1000)
36
+ let sinceLoad = Store.bundleSelectedAt > 0 ? (now - Store.bundleSelectedAt) * 1000 : -1
37
+ let promoted = ShipvoBundleSelector.promoteIfRunning(s)
38
+ return ["release": Store.runningRelease, "coldStartMs": Int(coldStart), "sinceLoadMs": Int(sinceLoad), "promoted": promoted,
39
+ "kind": Store.loadsInProcess <= 1 ? "cold" : "reload"]
40
+ }
41
+
42
+ Function("consumeEvents") { () -> [String] in Store().consumeEvents() }
43
+
44
+ Function("rollback") { () in
45
+ let s = Store()
46
+ Store.lock.lock()
47
+ if let p = s.pendingPath { try? FileManager.default.removeItem(atPath: p) }
48
+ s.pendingPath = nil; s.pendingRelease = 0; s.trialBoots = 0
49
+ s.addEvent("rolled_back:\(s.currentRelease)")
50
+ s.block(s.currentRelease)
51
+ ShipvoBundleSelector.revertToPrevious(s)
52
+ Store.lock.unlock()
53
+ Self.reloadHost()
54
+ }
55
+
56
+ Function("reload") { () in Self.reloadHost() }
57
+ }
58
+
59
+ static func reloadHost() {
60
+ ShipvoBundleSelector.invalidate()
61
+ DispatchQueue.main.async { RCTTriggerReloadCommandListeners("shipvo-update") }
62
+ }
63
+
64
+ /// Seconds since 1970 at which this process started.
65
+ static func processStart() -> TimeInterval {
66
+ var info = kinfo_proc(); var size = MemoryLayout<kinfo_proc>.stride
67
+ var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
68
+ guard sysctl(&mib, 4, &info, &size, nil, 0) == 0 else { return Date().timeIntervalSince1970 }
69
+ let t = info.kp_proc.p_un.__p_starttime
70
+ return TimeInterval(t.tv_sec) + TimeInterval(t.tv_usec) / 1_000_000
71
+ }
72
+ }
@@ -0,0 +1,102 @@
1
+ import Foundation
2
+
3
+ /// Persistent runtime state. Every bundle decision goes through here so the host handler and the module agree.
4
+ /// Mirrors the Android `Store`: same fields, same meaning.
5
+ final class Store {
6
+ /// Replaces what the app's Info.plist and file system would say. Tests use it; the app never does.
7
+ struct Overrides {
8
+ var suite: String, dir: URL, baseUrl: String, publicKey: String, appId: String, shellMajor: Int, shellVersion: String, binaryVersion: String
9
+ }
10
+
11
+ private let d: UserDefaults
12
+ private let bundle: Bundle
13
+ private let o: Overrides?
14
+
15
+ init(bundle: Bundle = .main, overrides: Overrides? = nil) {
16
+ self.bundle = bundle; self.o = overrides
17
+ self.d = UserDefaults(suiteName: overrides?.suite ?? "shipvo.runtime") ?? .standard
18
+ }
19
+
20
+ var dir: URL {
21
+ let base = o?.dir ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("shipvo", isDirectory: true)
22
+ try? FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
23
+ return base
24
+ }
25
+
26
+ // MARK: cohort and band
27
+ var cohort: Int {
28
+ if d.object(forKey: "cohort") == nil { d.set(Int.random(in: 0..<1000), forKey: "cohort") }
29
+ return d.integer(forKey: "cohort")
30
+ }
31
+ var band: String { let c = cohort; return c < 10 ? "b0" : (c < 100 ? "b1" : "b2") }
32
+
33
+ // MARK: releases
34
+ var currentRelease: Int { get { d.integer(forKey: "current_release") } set { d.set(newValue, forKey: "current_release") } }
35
+ var currentPath: String? { get { d.string(forKey: "current_path") } set { d.set(newValue, forKey: "current_path") } }
36
+ var currentSha: String? { get { d.string(forKey: "current_sha") } set { d.set(newValue, forKey: "current_sha") } }
37
+ var previousRelease: Int { get { d.integer(forKey: "previous_release") } set { d.set(newValue, forKey: "previous_release") } }
38
+ var previousPath: String? { get { d.string(forKey: "previous_path") } set { d.set(newValue, forKey: "previous_path") } }
39
+ var pendingRelease: Int { get { d.integer(forKey: "pending_release") } set { d.set(newValue, forKey: "pending_release") } }
40
+ var pendingPath: String? { get { d.string(forKey: "pending_path") } set { d.set(newValue, forKey: "pending_path") } }
41
+ var pendingSha: String? { get { d.string(forKey: "pending_sha") } set { d.set(newValue, forKey: "pending_sha") } }
42
+ var pendingIssuedAt: String? { get { d.string(forKey: "pending_issued_at") } set { d.set(newValue, forKey: "pending_issued_at") } }
43
+ /// Highest release this device refused (crash-looped or rolled back). Only newer releases are fetched.
44
+ var blockedRelease: Int { get { d.integer(forKey: "blocked_release") } set { d.set(newValue, forKey: "blocked_release") } }
45
+ /// Shell binary the stored OTA bundles were downloaded under.
46
+ var binaryVersion: String? { get { d.string(forKey: "binary_version") } set { d.set(newValue, forKey: "binary_version") } }
47
+ func block(_ release: Int) { if release > blockedRelease { blockedRelease = release } }
48
+
49
+ var trialBoots: Int { get { d.integer(forKey: "trial_boots") } set { d.set(newValue, forKey: "trial_boots") } }
50
+ var unhealthyBoots: Int { get { d.integer(forKey: "unhealthy_boots") } set { d.set(newValue, forKey: "unhealthy_boots") } }
51
+ var firstUnhealthyAt: Double { get { d.double(forKey: "first_unhealthy_at") } set { d.set(newValue, forKey: "first_unhealthy_at") } }
52
+
53
+ var installedBinaryVersion: String {
54
+ if let o { return o.binaryVersion }
55
+ let v = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
56
+ let b = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"
57
+ return "\(v)/\(b)"
58
+ }
59
+ /// The marketing version alone, compared against `min_shell_version`.
60
+ var shellVersion: String { if let o { return o.shellVersion }; return bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0" }
61
+
62
+ /// After a shell (app binary) update, bundles built for the old native code must not run.
63
+ func resetForNewShell() {
64
+ if let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) {
65
+ for f in files { try? FileManager.default.removeItem(at: f) }
66
+ }
67
+ for k in ["current_release", "current_path", "current_sha", "previous_release", "previous_path", "pending_release", "pending_path",
68
+ "pending_sha", "pending_issued_at", "trial_boots", "unhealthy_boots", "first_unhealthy_at", "blocked_release"] { d.removeObject(forKey: k) }
69
+ binaryVersion = installedBinaryVersion
70
+ }
71
+
72
+ // MARK: events
73
+ func addEvent(_ e: String) {
74
+ var list = (d.string(forKey: "events") ?? "").split(separator: "\n").map(String.init).filter { !$0.isEmpty }
75
+ list = Array(list.suffix(49)) + [e]
76
+ d.set(list.joined(separator: "\n"), forKey: "events")
77
+ }
78
+ func consumeEvents() -> [String] {
79
+ let list = (d.string(forKey: "events") ?? "").split(separator: "\n").map(String.init).filter { !$0.isEmpty }
80
+ d.removeObject(forKey: "events"); return list
81
+ }
82
+
83
+ // MARK: trust root (Info.plist, written by the config plugin; an OTA bundle cannot change these)
84
+ private func plist(_ key: String) -> String? { bundle.object(forInfoDictionaryKey: key) as? String }
85
+ var baseUrl: String { var s = o?.baseUrl ?? plist("ShipvoBaseURL") ?? ""; while s.hasSuffix("/") { s.removeLast() }; return s }
86
+ var publicKey: String { o?.publicKey ?? plist("ShipvoPublicKey") ?? "" }
87
+ var appId: String { o?.appId ?? plist("ShipvoAppId") ?? "" }
88
+ var shellMajor: Int { if let o { return o.shellMajor }; return Int(plist("ShipvoShellMajor") ?? "1") ?? 1 }
89
+
90
+ // MARK: per-process state
91
+ /// Which release the JS running right now came from (set when the bundle is selected).
92
+ static var runningRelease = 0
93
+ static var bundleSelectedAt: TimeInterval = 0
94
+ /// How many times a bundle was selected in this process: 1 = cold start, more = in-process reload.
95
+ static var loadsInProcess = 0
96
+ /// The URL chosen for the current load. React Native asks for the bundle URL more than once per load,
97
+ /// so the choice (and its trial-boot accounting) is made once and cached until a reload clears it.
98
+ static var selection: (url: URL?, set: Bool) = (nil, false)
99
+ static let lock = NSRecursiveLock()
100
+
101
+ static func now() -> TimeInterval { ProcessInfo.processInfo.systemUptime }
102
+ }
@@ -0,0 +1,73 @@
1
+ import Foundation
2
+
3
+ struct UpdateError: Error { let message: String; init(_ m: String) { message = m } }
4
+
5
+ /// Fetch, verify and stage the newest signed release for this device's band. Mirrors Android `check()`.
6
+ /// iOS downloads full bundles only for now; a pointer's `patches` are ignored (an Android-only optimisation).
7
+ enum Updater {
8
+ private static func require(_ cond: Bool, _ msg: @autoclosure () -> String) throws { if !cond { throw UpdateError(msg()) } }
9
+
10
+ private static func request(_ url: String, etag: String?) throws -> URLRequest {
11
+ guard let u = URL(string: url) else { throw UpdateError("bad url \(url)") }
12
+ var r = URLRequest(url: u, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30)
13
+ if let etag { r.setValue(etag, forHTTPHeaderField: "If-None-Match") }
14
+ return r
15
+ }
16
+
17
+ private static func resolve(_ s: Store, _ url: String) -> String { url.hasPrefix("http") ? url : "\(s.baseUrl)/\(url.drop(while: { $0 == "/" }))" }
18
+
19
+ static func check(_ s: Store) async throws -> [String: Any] {
20
+ try require(!s.baseUrl.isEmpty && !s.publicKey.isEmpty && !s.appId.isEmpty, "runtime not configured")
21
+ let known = max(s.currentRelease, s.pendingRelease, s.blockedRelease)
22
+ let (data, resp) = try await URLSession.shared.data(for: request("\(s.baseUrl)/p/\(s.appId)/\(s.shellMajor)/ios/\(s.band).json", etag: known > 0 ? "\"\(known)\"" : nil))
23
+ let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
24
+ if code == 304 || code == 404 { return ["status": "none"] }
25
+ try require(code == 200, "pointer HTTP \(code)")
26
+ guard let envelope = try JSONSerialization.jsonObject(with: data) as? [String: Any],
27
+ let bodyStr = envelope["body"] as? String, let sig = envelope["signature"] as? String else { throw UpdateError("pointer is not an envelope") }
28
+
29
+ let t0 = Store.now()
30
+ try require(Verify.ed25519(Data(bodyStr.utf8), signatureB64: sig, publicKeyB64: s.publicKey), "pointer signature invalid")
31
+ guard let body = try JSONSerialization.jsonObject(with: Data(bodyStr.utf8)) as? [String: Any] else { throw UpdateError("pointer body unreadable") }
32
+ try require(body["platform"] as? String == "ios", "pointer is not for iOS")
33
+ try require(body["app_id"] as? String == s.appId && body["shell_major"] as? Int == s.shellMajor, "pointer for another app/shell")
34
+ guard let release = body["release"] as? Int else { throw UpdateError("pointer has no release") }
35
+ if release <= known { return ["status": "none"] }
36
+ try require(!Verify.semverLess(s.shellVersion, body["min_shell_version"] as? String ?? "0.0.0"), "shell too old for release \(release)")
37
+ let verifyPointerMs = (Store.now() - t0) * 1000
38
+
39
+ guard let core = body["core"] as? [String: Any], let wantSha = core["sha256"] as? String,
40
+ let wantSize = (core["size"] as? NSNumber)?.intValue, let url = core["url"] as? String else { throw UpdateError("pointer core incomplete") }
41
+ let tmp = s.dir.appendingPathComponent("dl-\(release).tmp")
42
+ try? FileManager.default.removeItem(at: tmp)
43
+
44
+ let d0 = Store.now()
45
+ let (fileURL, dresp) = try await URLSession.shared.download(for: request(resolve(s, url), etag: nil))
46
+ let dcode = (dresp as? HTTPURLResponse)?.statusCode ?? 0
47
+ try require(dcode == 200, "bundle HTTP \(dcode)")
48
+ try FileManager.default.moveItem(at: fileURL, to: tmp)
49
+ let downloadMs = (Store.now() - d0) * 1000
50
+
51
+ let v0 = Store.now()
52
+ let size = (try? FileManager.default.attributesOfItem(atPath: tmp.path)[.size] as? Int) ?? -1
53
+ let ok = try (size == wantSize && Verify.sha256Hex(file: tmp) == wantSha)
54
+ if !ok { try? FileManager.default.removeItem(at: tmp); s.addEvent("verify_failed:\(release)"); throw UpdateError("bundle hash/size mismatch") }
55
+ let verifyMs = (Store.now() - v0) * 1000 + verifyPointerMs
56
+
57
+ let dest = s.dir.appendingPathComponent("r\(release).hbc")
58
+ try? FileManager.default.removeItem(at: dest)
59
+ try FileManager.default.moveItem(at: tmp, to: dest)
60
+ stage(s, dest: dest, release: release, sha: wantSha, issuedAt: body["issued_at"] as? String)
61
+ return ["status": "staged", "release": release, "bytes": size, "via": "full", "bundleBytes": size,
62
+ "downloadMs": Int(downloadMs), "verifyMs": Int(verifyMs), "issuedAt": body["issued_at"] as? String ?? ""]
63
+ }
64
+
65
+ /// Synchronous so the lock is never held across a suspension point.
66
+ private static func stage(_ s: Store, dest: URL, release: Int, sha: String, issuedAt: String?) {
67
+ Store.lock.lock(); defer { Store.lock.unlock() }
68
+ if let p = s.pendingPath, p != dest.path { try? FileManager.default.removeItem(atPath: p) }
69
+ s.pendingPath = dest.path; s.pendingRelease = release; s.trialBoots = 0; s.pendingSha = sha
70
+ if s.binaryVersion == nil { s.binaryVersion = s.installedBinaryVersion }
71
+ s.pendingIssuedAt = issuedAt
72
+ }
73
+ }
@@ -0,0 +1,30 @@
1
+ import CryptoKit
2
+ import Foundation
3
+
4
+ enum Verify {
5
+ static func ed25519(_ message: Data, signatureB64: String, publicKeyB64: String) -> Bool {
6
+ guard let sig = Data(base64Encoded: signatureB64), let raw = Data(base64Encoded: publicKeyB64),
7
+ let key = try? Curve25519.Signing.PublicKey(rawRepresentation: raw) else { return false }
8
+ return key.isValidSignature(sig, for: message)
9
+ }
10
+
11
+ static func sha256Hex(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
12
+
13
+ static func sha256Hex(file url: URL) throws -> String {
14
+ let h = try FileHandle(forReadingFrom: url); defer { try? h.close() }
15
+ var hasher = SHA256()
16
+ while let chunk = try h.read(upToCount: 64 * 1024), !chunk.isEmpty { hasher.update(data: chunk) }
17
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
18
+ }
19
+
20
+ /// a < b for x.y.z
21
+ static func semverLess(_ a: String, _ b: String) -> Bool {
22
+ func parts(_ s: String) -> [Int] { s.split(separator: "-")[0].split(separator: ".").map { Int($0) ?? 0 } }
23
+ let pa = parts(a), pb = parts(b)
24
+ for i in 0..<3 {
25
+ let x = i < pa.count ? pa[i] : 0, y = i < pb.count ? pb[i] : 0
26
+ if x != y { return x < y }
27
+ }
28
+ return false
29
+ }
30
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
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.1",
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
+ "ios",
22
+ "app.plugin.js",
23
+ "expo-module.config.json",
24
+ "README.md"
25
+ ],
26
+ "peerDependencies": {
27
+ "expo": "*",
28
+ "expo-modules-core": "*",
29
+ "expo-constants": "*",
30
+ "react-native": "*"
31
+ },
32
+ "peerDependenciesMeta": {
33
+ "expo-constants": {
34
+ "optional": true
35
+ }
36
+ },
37
+ "keywords": [
38
+ "shipvo",
39
+ "expo",
40
+ "react-native",
41
+ "ota",
42
+ "over-the-air",
43
+ "updates",
44
+ "ed25519"
45
+ ],
46
+ "homepage": "https://github.com/shipvo/shipvo#readme",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "git+https://github.com/shipvo/shipvo.git",
50
+ "directory": "packages/runtime"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "provenance": true
55
+ }
6
56
  }
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+ (Android): "patch" when a bsdiff patch was applied, "full" otherwise. iOS always downloads "full". */
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 native runtime exists on Android and iOS. Where the module is missing (web, Expo Go, a shell built without it) the
31
+ // app runs its embedded bundle and live content, and still knows its control plane and app id from 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
+ };