Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): add opt-in native self-host OTA recovery

guyong2a826fe265a9
diff --git a/apps/mobile/.env.example b/apps/mobile/.env.example
index e12fe16be7..7c18456ed9 100644
--- a/apps/mobile/.env.example
+++ b/apps/mobile/.env.example
@@ -30,6 +30,10 @@ EXPO_PUBLIC_XDT_MOBILE_VOICE_LITELLM_BASE_URL=
# EXPO_PUBLIC_APP_VARIANT 构建变体标识(beta/prod/自建)
# EXPO_PUBLIC_BETA_DEV beta 开发模式门控
# EXPO_PUBLIC_XDT_OTA_SELFHOST 是否自建变体(=1)
+# CINDY_MOBILE_OTA_NATIVE 自建原生 OTA 恢复(=1,改变 runtime,需新整包)
+# 不设置/0 保留旧 bridge 原生配置;非自建不消费。
+# CINDY_MOBILE_UPDATES_URL 上述原生模式的固定 HTTPS 更新基址或 /manifest URL;
+# 由私有构建环境注入,不在仓库或本地 .env 填生产地址。
# EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL
# CindyDev 运行时切换用的 CN Release 清单基址;由构建 helper
# 从 config/endpoint.json 派生,不要在本地 .env 手填
diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js
index f07934b3a3..69833b80d6 100644
--- a/apps/mobile/app.config.js
+++ b/apps/mobile/app.config.js
@@ -9,8 +9,9 @@
// TapDB / Google 公开配置;EAS 云构建看不到 gitignored 文件,继续使用 EAS environment。
// - 自建分发变体(`EXPO_PUBLIC_XDT_OTA_SELFHOST=1`):
// · iOS 与 Android app identity 各自一个字段,可独立调整,互不影响。
-// · updates.url 只放稳定占位值;真实 mobile-update-server 地址由启动端点清单的
-// mobileUpdateBaseUrl 运行时覆写,不参与 build/fingerprint;
+// · 旧 bridge 模式用占位 updates.url,由 mobileUpdateBaseUrl 运行时覆写;
+// CINDY_MOBILE_OTA_NATIVE=1 则把构建注入的固定地址与共享 headers 写入原生,
+// 启用原生事务恢复,有意改变自建 runtime。两种模式不能互投原生不兼容的 OTA。
// · 保留 region scheme,但使用自建 bundle identity。此变体有意改变指纹,
// 但只在该 env 开启时生效,EAS 路径仍逐字节不变。
// - 不注入任何按 commit 变化的内容(如 git hash),避免 fingerprint 每次提交漂移。
@@ -338,8 +339,12 @@ module.exports = (context = {}) => {
// 自建门控用 EXPO_PUBLIC_XDT_OTA_SELFHOST:同一个 EXPO_PUBLIC 标志既在此决定
// bundleId / 原生 OTA 策略,又被 inline 进 JS 供运行时 IS_OTA_SELFHOST 判定,
- // 构建与运行时严格对齐。真实 OTA 地址不再作为构建 env 注入。
+ // 构建与运行时严格对齐。原生恢复模式另用非 EXPO_PUBLIC 构建开关显式启用。
if (selfHosted) {
+ const nativeOta = process.env.CINDY_MOBILE_OTA_NATIVE?.trim();
+ if (nativeOta && nativeOta !== '0' && nativeOta !== '1') {
+ throw new Error('CINDY_MOBILE_OTA_NATIVE must be 0 or 1');
+ }
// Android 自建线:versionCode 只在此自建分支注入(经 release-android-*.mjs 传入的
// XDT_ANDROID_VERSION_CODE),APK 覆盖安装 + NPKG md5 去重要求它单调递增。app.json 里
// **不声明** android.versionCode → 非自建 resolved config 逐字节不变(红线 1,EAS 指纹不受影响)。
@@ -364,6 +369,24 @@ module.exports = (context = {}) => {
disableAntiBrickingMeasures: true,
},
};
+
+ // Explicit build-time rollout switch. Keeping the legacy configuration
+ // available permits the already shipped bridge runtime to remain frozen.
+ // Never detect this native capability from mutable OTA manifest extras.
+ if (nativeOta === '1') {
+ const { resolveUpdatesUrl, requestHeaders, nativeSourceHash } = require('./plugins/selfhost-ota/contract');
+ next = {
+ ...next,
+ plugins: [...next.plugins, ['./plugins/with-selfhost-ota', { sourceHash: nativeSourceHash() }]],
+ updates: {
+ ...next.updates,
+ url: resolveUpdatesUrl(process.env.CINDY_MOBILE_UPDATES_URL),
+ requestHeaders: requestHeaders('release'),
+ checkAutomatically: 'NEVER',
+ disableAntiBrickingMeasures: false,
+ },
+ };
+ }
}
return next;
diff --git a/apps/mobile/docs/selfhost-native-ota-recovery.md b/apps/mobile/docs/selfhost-native-ota-recovery.md
new file mode 100644
index 0000000000..82b00416fe
--- /dev/null
+++ b/apps/mobile/docs/selfhost-native-ota-recovery.md
@@ -0,0 +1,102 @@
+# 自建 Mobile 原生 OTA 恢复
+
+本功能只在显式启用的自建整包中装配。它不是已上线 JS bridge 的直接 OTA 替代品;
+原生能力改变后必须发布新整包,旧 runtime 的 bridge 和下载指针需要继续保留。
+商业发布配置与实际更新地址仍由维护者的私有构建环境管理。
+
+## 构建契约
+
+- 自建构建设置 `EXPO_PUBLIC_XDT_OTA_SELFHOST=1`、`CINDY_MOBILE_OTA_NATIVE=1`,并注入
+ `CINDY_MOBILE_UPDATES_URL`。地址必须使用 HTTPS,不允许凭据、query 或 fragment。
+ 地址成为原生 runtime 输入,不能再随运行期端点清单任意切换。
+- 未设置原生开关或设置为 `0` 时保留原来的 bridge 原生配置。非自建构建不装配适配器,
+ 也不因这些变量改变其 Expo 配置。开关是内部构建控制,不是用户设置。
+- 原生默认与每次通道切换均使用同一共享 `EAS-Client-ID`,release 的通道值固定为空字符串,
+ 不允许在缺 key、空值、`null` reset 三种下载身份之间混用。
+- 保持 `checkAutomatically=NEVER`,开启 anti-bricking。OTA 检查仍由现有 JS 入口调度;
+ TapDB/隐私选择及账号资格不由本功能修改。
+- `with-selfhost-ota` 仅在生成的 Android/iOS 工程内复制并适配 `[email protected]`。
+ 不修改共享 `node_modules`、不引入全局 autolinking 模块。上游版本或任何挂点不匹配时
+ 构建失败;原生源码摘要进入 resolved plugin options,防止原生变化漏进 fingerprint。
+- Android 使用生成的 Expo 子工程;iOS 使用生成的 EXUpdates pod,并强制从源码编译,
+ 不能由未适配的预编译 framework 覆盖。
+
+## 持久状态与恢复边界
+
+原生私有状态包含 schema 版本、runtime、原生 URL、安装包 embedded ID、最后成功版本、
+下载候选及其时间、在途请求、被拒绝的候选 ID。没有账号、consent、用户 Beta 偏好或凭证。
+状态不进入设备备份。
+
+| 阶段 | 持久动作 | 进程中断后的行为 |
+| --- | --- | --- |
+| 新原生代际或 runtime | 创建本代际状态,重建完整 Expo override | 使用新包 embedded,不沿用旧 runtime OTA |
+| 同 runtime 覆盖安装 | 按真实 embedded ID 识别新包,仅移除旧 embedded 或更旧 OTA receipt | 不让旧 OTA 遮住更新的整包;同时间或更晚 OTA 仍保留 |
+| 开始检查/下载 | 先原子写 journal,再改 header | 未完成下载时恢复原成功版本 |
+| 原生下载完成 | 在通知 JS 前记录 pending | 允许下载候选启动,不依赖 JS finally |
+| 即将启动候选 | 原生记录启动尝试 | 最多两次未确认尝试,之后恢复成功版本 |
+| Expo content appeared | pending 成为 good | 不再因后续业务错误任意自动回滚 |
+| 首次内容出现前失败/资源损坏 | 拒绝 pending,恢复持久与内存配置 | 同进程也能选回 good;不可恢复时保留 Expo 整包兜底 |
+
+启动选择继续使用 Expo 的 runtime、scope、数据库 launchable 状态和资产校验。只有原生
+事务确认的 pending/good 可跨通道及 manifest-filter 边界匹配,不能启动任意历史缓存。
+Reaper 保留这两个 ID 及其关联资源;服务端 rollback 指令在原生已接受时清除对应 pin。
+本功能不另加服务端发布、回滚入口或新的下载器。
+
+覆盖安装时在 Expo 读取配置前恢复状态:旧 override 的空 header 或只有 channel 的形态也
+会被处理,不能只移除 URL。恢复同 runtime 时不重复清除有效 OTA。辅助文件写入失败时
+禁用新的 OTA 操作,不能因为 journal 写入失败让账号、业务数据或整个应用被清理。
+无可用 journal 时选择器只允许当前安装包的 embedded,不能回退到任意 release 缓存。
+
+embedded 的识别依据真实安装包 ID 和原生 URL/headers,不能假设 Expo 57 的 embedded
+没有 URL/headers。双端 embedded-only loader 每次注册当前内置版本,避免旧通道的
+manifest filters 阻止它入库;通用远端下载策略没有放宽。跨通道返回同 updateId、命中
+缓存时,下载 receipt 从实际数据库对象建立,不把新响应 headers 错当成旧缓存的身份。
+
+每次更换 React launcher 先退役旧错误恢复实例,再为新首屏建立恢复状态。旧队列中的
+content-appeared、延迟移除错误监听器及 relaunch 回调不再修改新一轮状态;不能只重置
+journal 而沿用已被裁剪的 Expo 错误恢复流程。
+
+JS 只负责串行调度、超时与同 ID 去重。发现新版原生方法后必须校验原生 ABI/runtime;
+异常时禁止回退到需要关闭 anti-bricking 的完整 URL override。旧二进制没有该方法,
+继续使用已上线 bridge;不能用可被 OTA manifest 改写的 extras 判断原生能力。
+
+## 验证与发布前门槛
+
+常规定向测试:`nativeAppConfig.test.ts`、`selfhostOtaPlugin.test.ts`、
+`nativeOtaRequestCoordinator.test.ts`、`nativeOtaRouting.test.ts` 和现有 OTA 入口/bridge 测试。
+
+原生状态测试使用生产 journal 源码和窄范围 Expo/平台边界替身,临时文件只写测试目录:
+
+- Swift:`node apps/mobile/scripts/test-selfhost-ota-native.mjs`,需要 Swift 编译器;
+ 同时对被适配的 Expo Swift 文件做语法检查。
+- Kotlin:`node apps/mobile/scripts/test-selfhost-ota-android.mjs`,显式提供
+ `CINDY_OTA_TEST_KOTLINC`、`CINDY_OTA_TEST_JDK_HOME`、`CINDY_OTA_TEST_JSON_JAR`。
+ 测试工具不自动安装系统软件,也不读用户设备的数据。
+
+这些测试不替代完整原生工程编译或设备验证。出包前必须再验证:
+
+1. Android/iOS 自建冷包和新 runtime OTA 使用相同构建输入;分别核对两区域指纹。
+2. 非自建 Android/iOS 指纹与同依赖、同环境基线一致。
+3. 旧包覆盖安装、干净 SSO、普通账号切 SSO 后开 Beta、无新版、断网及超时。
+4. 在改 header、完成下载、启动候选前后强杀,核对真实 updateId 和运行来源。
+5. 候选首次启动失败、资源缺失、磁盘写入失败及缓存回收后的离线回退。
+6. 不覆盖旧 runtime 的 bridge/通道指针;是否持续维护旧 runtime 需另有发布机制。
+
+本改动属于冷更及更新器原生适配,指定把关人明确确认前不得合并或发布。确认要求见
+`docs/dev-rules/mobile-development.md`。
+
+## 本地验证记录(2026-09-07)
+
+- Mobile 全量单测:376 个文件、4,698 项通过;typecheck、scope、smoke 及根目录
+ `pnpm test:unit:related` 均通过。
+- Swift 与 Kotlin 生产 journal 均已编译并运行边界替身测试,覆盖强杀窗口、启动确认、
+ 跨通道缓存身份、同 runtime 覆盖安装及 I/O 不可用。适配后的 Expo Swift 文件通过语法检查。
+- 隔离临时项目的 Android/iOS `expo prebuild --no-install` 通过;生成工程含专属原生
+ 适配依赖、固定测试 URL 和完整共享 headers。没有修改工作区的生成工程或共享依赖源码。
+- 用同一依赖环境、虚拟构建配置对比基线与本分支,CN/Global × Android/iOS 四组均符合:
+ 非自建不变、旧 bridge 模式不变、启用原生模式改变指纹。这里验证变化范围,具体发版
+ runtime 仍由私有流水线用真实构建输入计算,不能拿测试环境 hash 发布。
+- 尚未做完整 Android/iOS 原生工程编译和设备验收,尤其新一轮首屏错误恢复的真实 React
+ 生命周期、磁盘故障、强杀及离线资产恢复;以上替身测试和 prebuild 不代表这些项目通过。
+- 本轮未修改私有构建流水线、启用生产开关或发布任何产物。接入流水线时,新整包及后续
+ 同 runtime OTA 必须同时使用上述原生构建变量;旧 runtime bridge 指针另行保留。
diff --git a/apps/mobile/plugins/selfhost-ota/android/CindyOtaJournal.kt b/apps/mobile/plugins/selfhost-ota/android/CindyOtaJournal.kt
new file mode 100644
index 0000000000..8ab920196b
--- /dev/null
+++ b/apps/mobile/plugins/selfhost-ota/android/CindyOtaJournal.kt
@@ -0,0 +1,318 @@
+package expo.modules.updates
+
+import android.content.Context
+import android.util.AtomicFile
+import android.util.Log
+import expo.modules.updates.db.entity.UpdateEntity
+import expo.modules.updates.db.enums.UpdateStatus
+import org.json.JSONObject
+import java.io.File
+import java.util.UUID
+
+/**
+ * Self-host-only write-ahead journal. Compiled into the isolated Expo Updates
+ * source adapter, never autolinked into EAS builds. The journal is authoritative;
+ * Expo's persisted override is repaired from it before configuration is read.
+ * No account, consent, device identifier, token or user Beta preference lives here.
+ */
+internal object CindyOtaJournal {
+ private const val VERSION = 1
+ private const val MAX_ATTEMPTS = 2
+ private const val SHARED_ID = "00000000-0000-4000-8000-000000000000"
+ private const val CHANNEL_KEY = "x-cindy-update-channel"
+ private var storage: AtomicFile? = null
+ private var appContext: Context? = null
+ private var defaults: UpdatesConfiguration? = null
+ private var state: JSONObject? = null
+ private var writable = true
+ private var activeAttempt: String? = null
+ private var embeddedUpdate: UpdateEntity? = null
+
+ data class LaunchChoice(val update: UpdateEntity?)
+
+ fun headers(channel: String): Map<String, String> {
+ require(channel in listOf("release", "beta", "canary")) { "Invalid self-host OTA channel" }
+ return mapOf("EAS-Client-ID" to SHARED_ID, CHANNEL_KEY to if (channel == "release") "" else channel)
+ }
+
+ fun validateHeaders(value: Map<String, String>?) {
+ if (value == null) return
+ val raw = value[CHANNEL_KEY]
+ val channel = if (raw.isNullOrEmpty()) "release" else raw
+ require(value == headers(channel)) { "Self-host OTA requires canonical shared headers" }
+ }
+
+ @Synchronized
+ fun prepare(context: Context): UpdatesConfiguration {
+ writable = true
+ activeAttempt = null
+ embeddedUpdate = null
+ appContext = context.applicationContext
+ // Explicitly ignore any persisted legacy URL/header override while reading
+ // the new binary's identity. This also resolves file:fingerprint natively.
+ val original = UpdatesConfiguration(context, null, false, null)
+ check(original.originalEmbeddedRequestHeaders == headers("release")) { "Invalid native OTA header contract" }
+ check(!original.disableAntiBrickingMeasures) { "Native OTA requires anti-bricking protection" }
+ defaults = original
+ storage = AtomicFile(File(context.noBackupFilesDir, "cindy-selfhost-ota-v1.json"))
+ try {
+ val old = try { JSONObject(String(storage!!.readFully(), Charsets.UTF_8)) } catch (_: Exception) { null }
+ val compatible = old != null && old.optInt("version") == VERSION &&
+ old.optString("runtime") == original.getRuntimeVersion() &&
+ old.optString("url") == original.updateUrl.toString() && validState(old)
+ val next = if (compatible) JSONObject(old.toString()) else JSONObject()
+ .put("version", VERSION).put("runtime", original.getRuntimeVersion())
+ .put("url", original.updateUrl.toString())
+ // A process death abandons the request, not an already committed download.
+ next.remove("request")
+ persist(next)
+ saveOverride(if (compatible) currentHeaders() else null)
+ val effective = currentHeaders()
+ return UpdatesConfiguration.create(context, original,
+ if (effective == headers("release")) null else UpdatesConfigurationOverride(null, effective))
+ } catch (_: Exception) {
+ writable = false
+ state = null
+ runCatching { saveOverride(null) }
+ Log.w("CindySelfHostOTA", "Journal unavailable; using embedded safety configuration")
+ return original // Do not reread an override that could not be repaired.
+ }
+ }
+
+ private fun validReceipt(value: JSONObject?): Boolean {
+ if (value == null) return true
+ return try {
+ UUID.fromString(value.getString("id"))
+ headers(value.getString("channel"))
+ value.getBoolean("embedded")
+ value.getLong("commitTime")
+ value.optInt("attempts", 0) in 0..MAX_ATTEMPTS
+ } catch (_: Exception) { false }
+ }
+
+ private fun validState(value: JSONObject): Boolean =
+ validReceipt(value.optJSONObject("good")) && validReceipt(value.optJSONObject("pending"))
+
+ // Called only with the manifest read from this signed binary, before Expo's
+ // embedded loader / launch selection. Never from a remote manifest response.
+ @Synchronized
+ fun observeEmbedded(update: UpdateEntity) {
+ embeddedUpdate = update
+ if (!writable || state == null) return
+ try {
+ val next = cloneState()
+ if (next.optString("binaryId") == update.id.toString()) return
+ for (key in listOf("good", "pending")) {
+ val receipt = next.optJSONObject(key) ?: continue
+ if (receipt.getBoolean("embedded") || receipt.getLong("commitTime") < update.commitTime.time) next.remove(key)
+ }
+ next.put("binaryId", update.id.toString())
+ persist(next)
+ saveOverride(currentHeaders())
+ } catch (_: Exception) {
+ writable = false
+ state = null
+ Log.w("CindySelfHostOTA", "Unable to migrate binary identity; using embedded safety configuration")
+ }
+ }
+
+ private fun isCurrentEmbedded(update: UpdateEntity, config: UpdatesConfiguration): Boolean =
+ update.id == embeddedUpdate?.id && update.status == UpdateStatus.EMBEDDED &&
+ update.runtimeVersion == config.getRuntimeVersion() && update.scopeKey == config.scopeKey &&
+ update.url == defaults?.updateUrl && update.requestHeaders == headers("release")
+
+ private fun cloneState(): JSONObject {
+ check(writable && state != null) { "Self-host OTA journal unavailable" }
+ return JSONObject(state.toString())
+ }
+
+ private fun persist(next: JSONObject) {
+ val file = checkNotNull(storage)
+ val stream = file.startWrite()
+ try {
+ stream.write(next.toString().toByteArray(Charsets.UTF_8))
+ stream.fd.sync()
+ file.finishWrite(stream)
+ } catch (error: Exception) {
+ file.failWrite(stream)
+ throw error
+ }
+ state = next
+ }
+
+ private fun saveOverride(requestHeaders: Map<String, String>?) {
+ val context = checkNotNull(appContext)
+ val editor = context.getSharedPreferences("dev.expo.updates.prefs", Context.MODE_PRIVATE).edit()
+ if (requestHeaders == null || requestHeaders == headers("release")) {
+ editor.remove("updatesConfigOverride")
+ } else {
+ // Rebuild the complete entry: saveRequestHeaders alone preserves old URLs.
+ editor.putString("updatesConfigOverride", JSONObject().put("requestHeaders", JSONObject(requestHeaders)).toString())
+ }
+ check(editor.commit()) { "Unable to persist self-host OTA headers" }
+ }
+
+ @Synchronized
+ fun capabilities(): Map<String, Any> = mapOf(
+ "version" to VERSION,
+ "runtimeVersion" to (defaults?.getRuntimeVersion() ?: ""),
+ "updateUrl" to (defaults?.updateUrl?.toString() ?: ""),
+ "available" to (writable && state != null)
+ )
+
+ @Synchronized
+ fun currentHeaders(): Map<String, String> {
+ val receipt = state?.optJSONObject("pending") ?: state?.optJSONObject("good")
+ return headers(receipt?.optString("channel") ?: "release")
+ }
+
+ @Synchronized
+ fun begin(channel: String): String {
+ val target = headers(channel)
+ val next = cloneState()
+ check(!next.has("request")) { "Self-host OTA request already in progress" }
+ val token = UUID.randomUUID().toString()
+ next.put("request", JSONObject().put("token", token).put("channel", channel))
+ persist(next) // Must complete before Expo persists a target header override.
+ try {
+ UpdatesController.instance.setUpdateRequestHeadersOverride(target)
+ } catch (error: Exception) {
+ finish(token)
+ throw error
+ }
+ return token
+ }
+
+ @Synchronized
+ fun finish(token: String) {
+ val next = cloneState()
+ if (next.optJSONObject("request")?.optString("token") != token) return
+ next.remove("request")
+ persist(next)
+ UpdatesController.instance.setUpdateRequestHeadersOverride(currentHeaders())
+ }
+
+ private fun snapshot(update: UpdateEntity): JSONObject? {
+ val config = defaults ?: return null
+ if (update.runtimeVersion != config.getRuntimeVersion() || update.scopeKey != config.scopeKey) return null
+ val embedded = isCurrentEmbedded(update, config)
+ val rawChannel = update.requestHeaders?.get(CHANNEL_KEY)
+ val channel = if (rawChannel.isNullOrEmpty()) "release" else rawChannel
+ if (!embedded && (update.url != config.updateUrl || update.requestHeaders != headers(channel))) return null
+ return JSONObject().put("id", update.id.toString()).put("channel", channel)
+ .put("embedded", embedded).put("attempts", 0).put("commitTime", update.commitTime.time)
+ }
+
+ @Synchronized
+ fun downloaded(update: UpdateEntity, config: UpdatesConfiguration) {
+ val next = cloneState()
+ val request = next.optJSONObject("request") ?: return
+ check(config.requestHeaders == headers(request.getString("channel"))) { "Stale self-host OTA download" }
+ val receipt = checkNotNull(snapshot(update)) { "Incompatible self-host OTA download" }
+ check(!isRejected(update.id.toString())) { "Previously failed self-host OTA update" }
+ if (receipt.getString("id") == next.optJSONObject("good")?.optString("id")) return
+ if (receipt.getString("id") == next.optJSONObject("pending")?.optString("id")) return
+ next.put("pending", receipt)
+ persist(next) // Native download has finished; do not depend on a JS callback.
+ }
+
+ private fun matches(update: UpdateEntity, receipt: JSONObject, config: UpdatesConfiguration): Boolean {
+ if (update.id.toString() != receipt.getString("id") || update.runtimeVersion != config.getRuntimeVersion() ||
+ update.scopeKey != config.scopeKey || isRejected(update.id.toString())) return false
+ if (update.failedLaunchCount > 0 && update.successfulLaunchCount == 0) return false
+ return if (receipt.getBoolean("embedded")) {
+ isCurrentEmbedded(update, config)
+ } else {
+ update.url == defaults?.updateUrl && update.requestHeaders == headers(receipt.getString("channel"))
+ }
+ }
+
+ @Synchronized
+ fun select(updates: List<UpdateEntity>, config: UpdatesConfiguration): LaunchChoice? {
+ val safeEmbedded = updates.filter { isCurrentEmbedded(it, config) }.maxByOrNull { it.commitTime }
+ val current = state ?: return LaunchChoice(safeEmbedded)
+ if (current.optString("runtime") != config.getRuntimeVersion() || current.optString("url") != config.updateUrl.toString()) return null
+ val pending = current.optJSONObject("pending")
+ if (pending != null) {
+ val candidate = updates.find { matches(it, pending, config) }
+ if (candidate != null && (pending.optInt("attempts") < MAX_ATTEMPTS || activeAttempt == pending.getString("id"))) return LaunchChoice(candidate)
+ try { reject(pending.getString("id")) } catch (_: Exception) { return LaunchChoice(null) }
+ }
+ state?.optJSONObject("good")?.let { good ->
+ updates.find { matches(it, good, config) }?.let { return LaunchChoice(it) }
+ }
+ // Only the two explicit receipts may cross channel/filter boundaries. Never
+ // broaden selection to arbitrary cached OTA updates or an abandoned download.
+ return LaunchChoice(safeEmbedded)
+ }
+
+ @Synchronized
+ fun selected(update: UpdateEntity) {
+ if (!writable || state == null) return
+ val next = cloneState()
+ val pending = next.optJSONObject("pending") ?: return
+ if (pending.getString("id") != update.id.toString()) return
+ if (activeAttempt == pending.getString("id")) return
+ pending.put("attempts", pending.optInt("attempts") + 1)
+ persist(next)
+ activeAttempt = pending.getString("id")
+ }
+
+ @Synchronized
+ fun confirmed(update: UpdateEntity) {
+ if (!writable || state == null) return
+ val receipt = snapshot(update) ?: return
+ val next = cloneState()
+ next.put("good", receipt)
+ if (next.optJSONObject("pending")?.optString("id") == update.id.toString()) next.remove("pending")
+ try {
+ persist(next)
+ activeAttempt = null
+ } catch (_: Exception) {
+ Log.w("CindySelfHostOTA", "Unable to confirm launch; retaining previous safe receipt")
+ }
+ }
+
+ private fun isRejected(id: String): Boolean = state?.optJSONObject("rejected")?.optBoolean(id) == true
+
+ private fun reject(id: String) {
+ val next = cloneState()
+ if (next.optJSONObject("pending")?.optString("id") == id) next.remove("pending")
+ val rejected = next.optJSONObject("rejected") ?: JSONObject()
+ rejected.put(id, true)
+ next.put("rejected", rejected)
+ persist(next)
+ activeAttempt = null
+ saveOverride(currentHeaders())
+ }
+
+ @Synchronized
+ fun failed(update: UpdateEntity?): Boolean {
+ if (!writable || update == null || state?.optJSONObject("pending")?.optString("id") != update.id.toString()) return false
+ return try {
+ reject(update.id.toString())
+ // Same-process error recovery also needs the controller's in-memory config.
+ UpdatesController.instance.setUpdateRequestHeadersOverride(currentHeaders())
+ true
+ } catch (_: Exception) {
+ Log.w("CindySelfHostOTA", "Unable to restore launch configuration")
+ false
+ }
+ }
+
+ @Synchronized
+ fun pinned(id: UUID): Boolean = listOf("good", "pending").any {
+ state?.optJSONObject(it)?.optString("id") == id.toString()
+ }
+
+ @Synchronized
+ fun rolledBackToEmbedded() {
+ val next = cloneState()
+ next.remove("good")
+ next.remove("pending")
+ persist(next)
+ activeAttempt = null
+ saveOverride(null)
+ UpdatesController.instance.setUpdateRequestHeadersOverride(headers("release"))
+ }
+}
diff --git a/apps/mobile/plugins/selfhost-ota/contract.js b/apps/mobile/plugins/selfhost-ota/contract.js
new file mode 100644
index 0000000000..1255ee3e68
--- /dev/null
+++ b/apps/mobile/plugins/selfhost-ota/contract.js
@@ -0,0 +1,60 @@
+// Native ABI: changing this contract requires a new self-host runtime.
+const NATIVE_OTA_VERSION = 1;
+const EXPO_UPDATES_VERSION = '57.0.18';
+const SHARED_CLIENT_ID = '00000000-0000-4000-8000-000000000000';
+const CHANNEL_HEADER = 'x-cindy-update-channel';
+
+function nativeSourceHash(readSource) {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const hash = require('node:crypto').createHash('sha256');
+ const read = readSource ?? ((file) => fs.readFileSync(path.join(__dirname, file)));
+ // Expo tracks imported JS plugins, not native files read later by a dangerous
+ // mod. Include their digest in resolved plugin options so any native adapter
+ // change necessarily changes the self-host runtime fingerprint.
+ for (const file of ['contract.js', 'patches.js', '../with-selfhost-ota.js',
+ 'android/CindyOtaJournal.kt', 'ios/CindyOtaJournal.swift']) {
+ hash.update(file + '\0').update(read(file));
+ }
+ return hash.digest('hex');
+}
+
+function requestHeaders(channel = 'release') {
+ if (!['release', 'beta', 'canary'].includes(channel)) {
+ throw new Error('Invalid self-host OTA channel');
+ }
+ // Omitted and empty headers are different Expo download identities. Always
+ // include both keys, including in the native default and rollback configuration.
+ return {
+ 'EAS-Client-ID': SHARED_CLIENT_ID,
+ [CHANNEL_HEADER]: channel === 'release' ? '' : channel,
+ };
+}
+
+function resolveUpdatesUrl(raw) {
+ if (typeof raw !== 'string' || !raw.trim()) {
+ throw new Error('Native self-host OTA requires CINDY_MOBILE_UPDATES_URL at build time');
+ }
+ let url;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ throw new Error('Invalid CINDY_MOBILE_UPDATES_URL');
+ }
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
+ throw new Error('CINDY_MOBILE_UPDATES_URL must use HTTPS without credentials, query or fragment');
+ }
+ const pathname = url.pathname.replace(/\/+$/, '');
+ url.pathname = pathname.endsWith('/manifest') ? pathname : pathname + '/manifest';
+ return url.toString();
+}
+
+module.exports = {
+ NATIVE_OTA_VERSION,
+ EXPO_UPDATES_VERSION,
+ SHARED_CLIENT_ID,
+ CHANNEL_HEADER,
+ requestHeaders,
+ resolveUpdatesUrl,
+ nativeSourceHash,
+};
diff --git a/apps/mobile/plugins/selfhost-ota/ios/CindyOtaJournal.swift b/apps/mobile/plugins/selfhost-ota/ios/CindyOtaJournal.swift
new file mode 100644
index 0000000000..27d91ac831
--- /dev/null
+++ b/apps/mobile/plugins/selfhost-ota/ios/CindyOtaJournal.swift
@@ -0,0 +1,309 @@
+import Foundation
+
+// Compiled only inside the isolated self-host EXUpdates source adapter. The
+// atomic journal, not UserDefaults or JS AsyncStorage, owns update transactions.
+enum CindyOtaJournal {
+ private static let version = 1
+ private static let maximumAttempts = 2
+ private static let sharedID = "00000000-0000-4000-8000-000000000000"
+ private static let channelKey = "x-cindy-update-channel"
+ private static let lock = NSRecursiveLock()
+ private static var file: URL?
+ private static var defaults: UpdatesConfig?
+ private static var state: Journal?
+ private static var writable = true
+ private static var activeAttempt: String?
+ private static var embeddedUpdate: Update?
+
+ private struct Receipt: Codable {
+ let id: String
+ let channel: String
+ let embedded: Bool
+ let commitTime: Date
+ var attempts = 0
+ }
+ private struct Request: Codable {
+ let token: String
+ let channel: String
+ }
+ private struct Journal: Codable {
+ var version: Int
+ var runtime: String
+ var url: String
+ var binaryId: String?
+ var good: Receipt?
+ var pending: Receipt?
+ var request: Request?
+ var rejected: [String: Bool] = [:]
+ }
+ struct LaunchChoice {
+ let update: Update?
+ }
+
+ private static func locked<T>(_ operation: () throws -> T) rethrows -> T {
+ lock.lock()
+ defer { lock.unlock() }
+ return try operation()
+ }
+ private static func failure(_ message: String) -> NSError {
+ NSError(domain: "CindySelfHostOTA", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
+ }
+ static func headers(_ channel: String) throws -> [String: String] {
+ guard ["release", "beta", "canary"].contains(channel) else {
+ throw failure("Invalid self-host OTA channel")
+ }
+ return ["EAS-Client-ID": sharedID, channelKey: channel == "release" ? "" : channel]
+ }
+ static func validateHeaders(_ value: [String: String]?) throws {
+ guard let value else { return }
+ let rawChannel = value[channelKey] ?? ""
+ guard value == (try headers(rawChannel.isEmpty ? "release" : rawChannel)) else {
+ throw failure("Self-host OTA requires canonical shared headers")
+ }
+ }
+
+ @discardableResult
+ static func prepare(storageDirectoryForTesting: URL? = nil) throws -> UpdatesConfig {
+ try locked {
+ writable = true
+ let original = try UpdatesConfig.cindyEmbeddedConfiguration()
+ guard original.originalEmbeddedRequestHeaders == (try headers("release")),
+ !original.disableAntiBrickingMeasures else {
+ throw failure("Invalid native OTA header contract")
+ }
+ defaults = original
+ activeAttempt = nil
+ embeddedUpdate = nil
+ do {
+ let directory = try storageDirectoryForTesting ?? FileManager.default.url(for: .applicationSupportDirectory,
+ in: .userDomainMask, appropriateFor: nil, create: true)
+ .appendingPathComponent("CindySelfHostOTA", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ var excluded = directory
+ var values = URLResourceValues()
+ values.isExcludedFromBackup = true
+ try excluded.setResourceValues(values)
+ file = directory.appendingPathComponent("journal-v1.json")
+ let old = try? JSONDecoder().decode(Journal.self, from: Data(contentsOf: file!))
+ let compatible = old.map {
+ $0.version == version && $0.runtime == original.runtimeVersion &&
+ $0.url == original.updateUrl.absoluteString && valid($0.good) && valid($0.pending)
+ } ?? false
+ var next = compatible ? old! : Journal(version: version, runtime: original.runtimeVersion,
+ url: original.updateUrl.absoluteString)
+ next.request = nil
+ try persist(next)
+ saveOverride(compatible ? try currentHeaders() : nil)
+ let effective = try currentHeaders()
+ let configOverride = effective == (try headers("release")) ? nil
+ : UpdatesConfigOverride(updateUrl: nil, requestHeaders: effective)
+ return try UpdatesConfig.config(fromConfig: original, configOverride: configOverride)
+ } catch {
+ writable = false
+ state = nil
+ saveOverride(nil)
+ NSLog("[CindySelfHostOTA] Journal unavailable; using embedded safety configuration")
+ return original
+ }
+ }
+ }
+
+ private static func valid(_ receipt: Receipt?) -> Bool {
+ guard let receipt else { return true }
+ return UUID(uuidString: receipt.id) != nil && (try? headers(receipt.channel)) != nil &&
+ receipt.attempts >= 0 && receipt.attempts <= maximumAttempts
+ }
+ // The caller is the embedded-only loader and supplies the signed binary's
+ // manifest, never a remote response. Receipt pruning happens once per binary.
+ static func observeEmbedded(_ update: Update) {
+ locked {
+ embeddedUpdate = update
+ guard writable, state != nil else { return }
+ do {
+ var next = try loadState()
+ let id = update.updateId.uuidString.lowercased()
+ guard next.binaryId != id else { return }
+ if let good = next.good, good.embedded || good.commitTime < update.commitTime { next.good = nil }
+ if let pending = next.pending, pending.embedded || pending.commitTime < update.commitTime { next.pending = nil }
+ next.binaryId = id
+ try persist(next)
+ saveOverride(try currentHeaders())
+ } catch {
+ writable = false
+ state = nil
+ NSLog("[CindySelfHostOTA] Unable to migrate binary identity; using embedded safety configuration")
+ }
+ }
+ }
+ private static func isCurrentEmbedded(_ update: Update, config: UpdatesConfig) -> Bool {
+ update.updateId == embeddedUpdate?.updateId && update.status == .StatusEmbedded &&
+ update.runtimeVersion == config.runtimeVersion && update.scopeKey == config.scopeKey &&
+ update.url == defaults?.updateUrl && update.requestHeaders == (try? headers("release"))
+ }
+ private static func loadState() throws -> Journal {
+ guard writable, let state else { throw failure("Self-host OTA journal unavailable") }
+ return state
+ }
+ private static func persist(_ next: Journal) throws {
+ guard let file else { throw failure("Self-host OTA journal unavailable") }
+ // Write-ahead, atomic rename. A process killed before the matching Expo
+ // UserDefaults write is repaired from this file on its next native startup.
+ try JSONEncoder().encode(next).write(to: file, options: .atomic)
+ state = next
+ }
+ private static func saveOverride(_ requestHeaders: [String: String]?) {
+ if requestHeaders == nil || requestHeaders == (try? headers("release")) {
+ UpdatesConfigOverride.save(configOverride: nil)
+ } else {
+ // Never preserve a legacy updateUrl hidden in UserDefaults.
+ UpdatesConfigOverride.save(configOverride: UpdatesConfigOverride(updateUrl: nil, requestHeaders: requestHeaders))
+ }
+ }
+ static func capabilities() -> [String: Any] {
+ locked {
+ ["version": version, "runtimeVersion": defaults?.runtimeVersion ?? "",
+ "updateUrl": defaults?.updateUrl.absoluteString ?? "", "available": writable && state != nil]
+ }
+ }
+ static func currentHeaders() throws -> [String: String] {
+ try locked { try headers((state?.pending ?? state?.good)?.channel ?? "release") }
+ }
+
+ static func begin(_ channel: String) throws -> String {
+ try locked {
+ let target = try headers(channel)
+ var next = try loadState()
+ guard next.request == nil else { throw failure("Self-host OTA request already in progress") }
+ let token = UUID().uuidString.lowercased()
+ next.request = Request(token: token, channel: channel)
+ try persist(next)
+ do {
+ try AppController.sharedInstance.setUpdateRequestHeadersOverride(target)
+ } catch {
+ try finish(token)
+ throw error
+ }
+ return token
+ }
+ }
+ static func finish(_ token: String) throws {
+ try locked {
+ var next = try loadState()
+ guard next.request?.token == token else { return }
+ next.request = nil
+ try persist(next)
+ try AppController.sharedInstance.setUpdateRequestHeadersOverride(currentHeaders())
+ }
+ }
+ private static func snapshot(_ update: Update) -> Receipt? {
+ guard let defaults, update.runtimeVersion == defaults.runtimeVersion,
+ update.scopeKey == defaults.scopeKey else { return nil }
+ let embedded = isCurrentEmbedded(update, config: defaults)
+ let rawChannel = update.requestHeaders?[channelKey] ?? ""
+ let channel = rawChannel.isEmpty ? "release" : rawChannel
+ guard embedded || (update.url == defaults.updateUrl && update.requestHeaders == (try? headers(channel))) else { return nil }
+ return Receipt(id: update.updateId.uuidString.lowercased(), channel: channel, embedded: embedded, commitTime: update.commitTime)
+ }
+ static func downloaded(_ update: Update, config: UpdatesConfig) throws {
+ try locked {
+ var next = try loadState()
+ guard let request = next.request else { return }
+ guard config.requestHeaders == (try headers(request.channel)), let receipt = snapshot(update),
+ next.rejected[receipt.id] != true else { throw failure("Incompatible or previously failed self-host OTA download") }
+ if next.good?.id == receipt.id || next.pending?.id == receipt.id { return }
+ next.pending = receipt
+ try persist(next)
+ }
+ }
+ private static func matches(_ update: Update, receipt: Receipt, config: UpdatesConfig) -> Bool {
+ guard update.updateId.uuidString.lowercased() == receipt.id, update.runtimeVersion == config.runtimeVersion,
+ update.scopeKey == config.scopeKey, state?.rejected[receipt.id] != true,
+ update.failedLaunchCount == 0 || update.successfulLaunchCount > 0 else { return false }
+ return receipt.embedded
+ ? isCurrentEmbedded(update, config: config)
+ : update.url == defaults?.updateUrl && update.requestHeaders == (try? headers(receipt.channel))
+ }
+ static func select(_ updates: [Update], config: UpdatesConfig) -> LaunchChoice? {
+ locked {
+ let safeEmbedded = updates.filter { isCurrentEmbedded($0, config: config) }.max(by: { $0.commitTime < $1.commitTime })
+ guard let current = state, current.runtime == config.runtimeVersion,
+ current.url == config.updateUrl.absoluteString else { return LaunchChoice(update: safeEmbedded) }
+ if let pending = current.pending {
+ if let candidate = updates.first(where: { matches($0, receipt: pending, config: config) }),
+ pending.attempts < maximumAttempts || activeAttempt == pending.id {
+ return LaunchChoice(update: candidate)
+ }
+ do { try reject(pending.id) } catch { return LaunchChoice(update: nil) }
+ }
+ if let good = state?.good,
+ let update = updates.first(where: { matches($0, receipt: good, config: config) }) {
+ return LaunchChoice(update: update)
+ }
+ // Database launchability/runtime/scope checks remain authoritative. Only
+ // receipts downloaded by this journal may cross channel/filter boundaries.
+ return LaunchChoice(update: safeEmbedded)
+ }
+ }
+ static func selected(_ update: Update) throws {
+ try locked {
+ guard writable, state != nil else { return }
+ var next = try loadState()
+ guard var pending = next.pending, pending.id == update.updateId.uuidString.lowercased() else { return }
+ guard activeAttempt != pending.id else { return }
+ pending.attempts += 1
+ next.pending = pending
+ try persist(next)
+ activeAttempt = pending.id
+ }
+ }
+ static func confirmed(_ update: Update) {
+ locked {
+ guard writable, state != nil, let receipt = snapshot(update) else { return }
+ do {
+ var next = try loadState()
+ next.good = receipt
+ if next.pending?.id == receipt.id { next.pending = nil }
+ try persist(next)
+ activeAttempt = nil
+ } catch {
+ NSLog("[CindySelfHostOTA] Unable to confirm launch; retaining previous safe receipt")
+ }
+ }
+ }
+ private static func reject(_ id: String) throws {
+ var next = try loadState()
+ if next.pending?.id == id { next.pending = nil }
+ next.rejected[id] = true
+ try persist(next)
+ activeAttempt = nil
+ saveOverride(try currentHeaders())
+ }
+ @discardableResult
+ static func failed(_ update: Update?) -> Bool {
+ locked {
+ guard writable, let update, state?.pending?.id == update.updateId.uuidString.lowercased() else { return false }
+ do {
+ try reject(update.updateId.uuidString.lowercased())
+ try AppController.sharedInstance.setUpdateRequestHeadersOverride(currentHeaders())
+ return true
+ } catch {
+ NSLog("[CindySelfHostOTA] Unable to restore launch configuration")
+ return false
+ }
+ }
+ }
+ static func pinned(_ id: UUID) -> Bool {
+ locked { [state?.good?.id, state?.pending?.id].contains(id.uuidString.lowercased()) }
+ }
+ static func rolledBackToEmbedded() throws {
+ try locked {
+ var next = try loadState()
+ next.good = nil
+ next.pending = nil
+ try persist(next)
+ activeAttempt = nil
+ saveOverride(nil)
+ try AppController.sharedInstance.setUpdateRequestHeadersOverride(headers("release"))
+ }
+ }
+}
diff --git a/apps/mobile/plugins/selfhost-ota/patches.js b/apps/mobile/plugins/selfhost-ota/patches.js
new file mode 100644
index 0000000000..8ccf57b0f1
--- /dev/null
+++ b/apps/mobile/plugins/selfhost-ota/patches.js
@@ -0,0 +1,255 @@
+// Deliberately small, version-locked integration points. These are applied to a
+// generated, self-host-only COPY of expo-updates, never to shared node_modules.
+// Every replacement must match exactly once (or its explicit expected count).
+const android = 'android/src/main/java/expo/modules/updates/';
+const ios = 'ios/EXUpdates/';
+const journal = 'expo.modules.updates.CindyOtaJournal';
+
+function patches() {
+ return [
+ [android + 'UpdatesController.kt',
+ ' val updatesConfiguration: UpdatesConfiguration? = overrideConfiguration ?: run {',
+ ' try { overrideConfiguration = CindyOtaJournal.prepare(context) } catch (error: Exception) {\n' +
+ ' logger.warn("Invalid self-host OTA native configuration")\n' +
+ ' singletonInstance = DisabledUpdatesController(context, error)\n return\n }\n\n' +
+ ' val updatesConfiguration: UpdatesConfiguration? = overrideConfiguration ?: run {'],
+ [android + 'UpdatesModule.kt', ' Name("ExpoUpdates")',
+ ' Name("ExpoUpdates")\n\n' +
+ ' Function("cindySelfHostOtaCapabilities") { CindyOtaJournal.capabilities() }\n' +
+ ' Function("cindyBeginSelfHostOtaRequest") { channel: String -> CindyOtaJournal.begin(channel) }\n' +
+ ' Function("cindyFinishSelfHostOtaRequest") { token: String -> CindyOtaJournal.finish(token) }'],
+ [android + 'EnabledUpdatesController.kt',
+ ' override fun setUpdateRequestHeadersOverride(requestHeaders: Map<String, String>?) {',
+ ' override fun setUpdateRequestHeadersOverride(requestHeaders: Map<String, String>?) {\n' +
+ ' CindyOtaJournal.validateHeaders(requestHeaders)'],
+ [android + 'loader/LoaderTask.kt',
+ ' val launchableUpdate = launcher.getLaunchableUpdate(database)\n val manifestFilters = ManifestMetadata.getManifestFilters(database, configuration)\n' +
+ ' if (selectionPolicy.shouldLoadNewUpdate(\n embeddedUpdate,\n launchableUpdate,\n manifestFilters\n )\n ) {',
+ ' ' + journal + '.observeEmbedded(embeddedUpdate)\n' +
+ ' // Register this signed binary even when old channel filters disagree.\n' +
+ ' // Existing rows are reused by EmbeddedLoader; remote policy is unchanged.\n' +
+ ' if (configuration.hasEmbeddedUpdate) {'],
+ [android + 'procedures/FetchUpdateProcedure.kt',
+ ' if (didRollBackToEmbedded) {',
+ ' if (didRollBackToEmbedded) {\n ' + journal + '.rolledBackToEmbedded()'],
+ [android + 'procedures/FetchUpdateProcedure.kt',
+ ' procedureContext.processStateEvent(UpdatesStateEvent.DownloadCompleteWithUpdate(availableUpdate.manifest))',
+ ' val cindyStoredUpdate = checkNotNull(databaseHolder.database.updateDao().loadUpdateWithId(availableUpdate.id))\n' +
+ ' ' + journal + '.downloaded(cindyStoredUpdate, updatesConfiguration)\n' +
+ ' procedureContext.processStateEvent(UpdatesStateEvent.DownloadCompleteWithUpdate(availableUpdate.manifest))'],
+ [android + 'selectionpolicy/LauncherSelectionPolicyFilterAware.kt',
+ ' ): UpdateEntity? =\n updates',
+ ' ): UpdateEntity? {\n ' + journal + '.select(updates, config)?.let { return it.update }\n return updates'],
+ [android + 'selectionpolicy/LauncherSelectionPolicyFilterAware.kt',
+ ' .maxByOrNull { it.commitTime }\n}',
+ ' .maxByOrNull { it.commitTime }\n }\n}'],
+ [android + 'selectionpolicy/ReaperSelectionPolicyFilterAware.kt',
+ ' return updatesToDelete.filter { it.status != UpdateStatus.EMBEDDED }',
+ ' return updatesToDelete.filter { it.status != UpdateStatus.EMBEDDED && !' + journal + '.pinned(it.id) }'],
+ [android + 'launcher/DatabaseLauncher.kt',
+ ' suspend fun launch(database: UpdatesDatabase) {',
+ ' suspend fun launch(database: UpdatesDatabase) {\n' +
+ ' try {\n launchOnce(database)\n' +
+ ' } catch (error: kotlinx.coroutines.CancellationException) {\n throw error\n' +
+ ' } catch (error: Exception) {\n' +
+ ' if (!' + journal + '.failed(launchedUpdate)) throw error\n' +
+ ' hasLaunched = false\n launchAssetException = null\n localAssetFiles = null\n' +
+ ' launchAssetFile = null\n launchOnce(database)\n }\n }\n\n' +
+ ' private suspend fun launchOnce(database: UpdatesDatabase) {'],
+ [android + 'launcher/DatabaseLauncher.kt',
+ ' database.updateDao().markUpdateAccessed(launchedUpdate!!)',
+ ' ' + journal + '.selected(launchedUpdate!!)\n database.updateDao().markUpdateAccessed(launchedUpdate!!)'],
+ [android + 'procedures/StartupProcedure.kt',
+ ' private val errorRecovery = ErrorRecovery(logger)',
+ ' private var errorRecovery = ErrorRecovery(logger)'],
+ [android + 'procedures/StartupProcedure.kt',
+ ' fun setLauncher(launcher: Launcher) {\n this.launcher = launcher\n }',
+ ' fun setLauncher(launcher: Launcher) {\n' +
+ ' errorRecovery = errorRecovery.cindyReplacement()\n' +
+ ' this.launcher = launcher\n initializeErrorRecovery()\n' +
+ ' errorRecovery.cindyResumeMonitoring()\n }'],
+ [android + 'errorrecovery/ErrorRecoveryHandler.kt',
+ ' private val pipeline = arrayListOf(',
+ ' private val cindyEpochLock = Any()\n private var cindyActive = true\n' +
+ ' override fun dispatchMessage(msg: Message) {\n' +
+ ' synchronized(cindyEpochLock) { if (cindyActive) super.dispatchMessage(msg) }\n }\n' +
+ ' internal fun cindyRetire() {\n' +
+ ' synchronized(cindyEpochLock) { cindyActive = false; removeCallbacksAndMessages(null) }\n }\n\n' +
+ ' private val pipeline = arrayListOf('],
+ [android + 'errorrecovery/ErrorRecovery.kt',
+ ' private var shouldHandleReactInstanceException = false',
+ ' private var shouldHandleReactInstanceException = false\n' +
+ ' private var cindyDevSupportManager: DevSupportManager? = null\n' +
+ ' internal fun cindyReplacement(): ErrorRecovery {\n' +
+ ' unregisterContentAppearedListener()\n unregisterErrorHandler()\n' +
+ ' if (::handler.isInitialized) {\n' +
+ ' (handler as ErrorRecoveryHandler).cindyRetire()\n handlerThread.quitSafely()\n }\n' +
+ ' return ErrorRecovery(logger).also { it.cindyDevSupportManager = cindyDevSupportManager }\n }\n' +
+ ' internal fun cindyResumeMonitoring() { cindyDevSupportManager?.let { startMonitoring(it) } }'],
+ [android + 'errorrecovery/ErrorRecovery.kt',
+ ' fun startMonitoring(devSupportManager: DevSupportManager) {',
+ ' fun startMonitoring(devSupportManager: DevSupportManager) {\n' +
+ ' cindyDevSupportManager = devSupportManager\n unregisterContentAppearedListener()'],
+ [android + 'procedures/StartupProcedure.kt',
+ ' override fun markFailedLaunchForLaunchedUpdate() {\n if (emergencyLaunchException != null) {\n return\n }',
+ ' override fun markFailedLaunchForLaunchedUpdate() {\n if (emergencyLaunchException != null) {\n return\n }\n' +
+ ' ' + journal + '.failed(launchedUpdate)'],
+ [android + 'procedures/StartupProcedure.kt',
+ ' override fun markSuccessfulLaunchForLaunchedUpdate() {\n if (emergencyLaunchException != null) {\n return\n }',
+ ' override fun markSuccessfulLaunchForLaunchedUpdate() {\n if (emergencyLaunchException != null) {\n return\n }\n' +
+ ' launchedUpdate?.let { ' + journal + '.confirmed(it) }'],
+
+ [ios + 'UpdatesConfig.swift',
+ ' public static func configWithExpoPlist(mergingOtherDictionary: [String: Any]?) throws -> UpdatesConfig {',
+ ' internal static func cindyEmbeddedConfiguration() throws -> UpdatesConfig {\n' +
+ ' let dictionary = try configDictionaryWithExpoPlist(mergingOtherDictionary: nil)\n' +
+ ' return try config(fromDictionary: dictionary, configOverride: nil)\n }\n\n' +
+ ' public static func configWithExpoPlist(mergingOtherDictionary: [String: Any]?) throws -> UpdatesConfig {'],
+ [ios + 'AppController.swift',
+ ' let config = _overrideConfig != nil ? _overrideConfig : {',
+ ' do { _overrideConfig = try CindyOtaJournal.prepare() } catch {\n' +
+ ' UpdatesLogger().warn(message: "Invalid self-host OTA native configuration")\n' +
+ ' _sharedInstance = DisabledAppController(error: UpdatesError.appControllerInitializationError(cause: error))\n return\n }\n\n' +
+ ' let config = _overrideConfig != nil ? _overrideConfig : {'],
+ [ios + 'UpdatesModule.swift', ' Name("ExpoUpdates")',
+ ' Name("ExpoUpdates")\n\n' +
+ ' Function("cindySelfHostOtaCapabilities") { CindyOtaJournal.capabilities() }\n' +
+ ' Function("cindyBeginSelfHostOtaRequest") { (channel: String) throws -> String in try CindyOtaJournal.begin(channel) }\n' +
+ ' Function("cindyFinishSelfHostOtaRequest") { (token: String) throws in try CindyOtaJournal.finish(token) }'],
+ [ios + 'EnabledAppController.swift',
+ ' public func setUpdateRequestHeadersOverride(_ requestHeaders: [String: String]?) throws {',
+ ' public func setUpdateRequestHeadersOverride(_ requestHeaders: [String: String]?) throws {\n' +
+ ' try CindyOtaJournal.validateHeaders(requestHeaders)'],
+ [ios + 'AppLoader/AppLoaderTask.swift',
+ ' private func loadEmbeddedUpdate(withCompletion completion: @escaping () -> Void) {',
+ ' private func loadEmbeddedUpdate(withCompletion completion: @escaping () -> Void) {\n' +
+ ' if let embedded = EmbeddedAppLoader.originalEmbeddedManifest(withConfig: config, database: database) {\n' +
+ ' CindyOtaJournal.observeEmbedded(embedded)\n }'],
+ [ios + 'AppLoader/AppLoaderTask.swift',
+ ' if self.config.hasEmbeddedUpdate && self.selectionPolicy.shouldLoadNewUpdate(\n' +
+ ' EmbeddedAppLoader.embeddedManifest(withConfig: self.config, database: self.database),\n' +
+ ' withLaunchedUpdate: launchableUpdate,\n filters: manifestFilters\n ) {',
+ ' // Register only this signed binary; stale OTA filters must not hide it.\n' +
+ ' if self.config.hasEmbeddedUpdate {'],
+ [ios + 'Procedures/FetchUpdateProcedure.swift',
+ ' if didRollBackToEmbedded {',
+ ' if didRollBackToEmbedded {\n' +
+ ' do { try CindyOtaJournal.rolledBackToEmbedded() } catch {\n' +
+ ' self.successBlock(FetchUpdateResult.error(error: error))\n' +
+ ' procedureContext.onComplete()\n return\n }'],
+ [ios + 'Procedures/FetchUpdateProcedure.swift',
+ ' if let update = updateToLaunch {\n self.successBlock(FetchUpdateResult.success(manifest: update.manifest.rawManifestJSON()))',
+ ' if let update = updateToLaunch {\n' +
+ ' do {\n' +
+ ' let stored = try self.database.databaseQueue.sync { try self.database.update(withId: update.updateId, config: self.config) }\n' +
+ ' guard let stored else { throw NSError(domain: "CindySelfHostOTA", code: 2) }\n' +
+ ' try CindyOtaJournal.downloaded(stored, config: self.config)\n' +
+ ' } catch {\n' +
+ ' self.successBlock(FetchUpdateResult.error(error: error))\n' +
+ ' procedureContext.processStateEvent(.downloadError(errorMessage: "Self-host OTA journal commit failed"))\n' +
+ ' procedureContext.onComplete()\n return\n }\n' +
+ ' self.successBlock(FetchUpdateResult.success(manifest: update.manifest.rawManifestJSON()))'],
+ [ios + 'SelectionPolicy/LauncherSelectionPolicyFilterAware.swift',
+ ' public func launchableUpdate(fromUpdates updates: [Update], filters: [String: Any]?) -> Update? {\n return updates',
+ ' public func launchableUpdate(fromUpdates updates: [Update], filters: [String: Any]?) -> Update? {\n' +
+ ' if let choice = CindyOtaJournal.select(updates, config: config) { return choice.update }\n return updates'],
+ [ios + 'SelectionPolicy/ReaperSelectionPolicyFilterAware.swift',
+ ' return updatesToDelete\n',
+ ' return updatesToDelete.filter { !CindyOtaJournal.pinned($0.updateId) }\n'],
+ [ios + 'Procedures/StartupProcedure.swift',
+ ' private let errorRecovery: ErrorRecovery',
+ ' private var errorRecovery: ErrorRecovery'],
+ [ios + 'Procedures/StartupProcedure.swift',
+ ' internal func setLauncher(_ launcher: AppLauncher) {\n self.launcher = launcher\n }',
+ ' internal func setLauncher(_ launcher: AppLauncher) {\n' +
+ ' errorRecovery.cindyRetire()\n self.launcher = launcher\n' +
+ ' errorRecovery = ErrorRecovery(logger: logger)\n errorRecovery.delegate = self\n }'],
+ [ios + 'ErrorRecovery.swift',
+ ' private var pipeline: [ErrorRecoveryTask]',
+ ' private var cindyActive = true\n private var cindyInstalledHandlers = false\n' +
+ ' internal func cindyRetire() {\n' +
+ ' unregisterObservers()\n errorRecoveryQueue.sync {\n' +
+ ' self.cindyActive = false\n' +
+ ' if self.cindyInstalledHandlers { self.unsetRCTErrorHandlers() }\n' +
+ ' self.delegate = nil\n }\n }\n\n' +
+ ' private var pipeline: [ErrorRecoveryTask]'],
+ [ios + 'ErrorRecovery.swift',
+ ' errorRecoveryQueue.async {',
+ ' errorRecoveryQueue.async {\n guard self.cindyActive else { return }', 4],
+ [ios + 'ErrorRecovery.swift',
+ ' self.errorRecoveryQueue.async {',
+ ' self.errorRecoveryQueue.async {\n guard self.cindyActive else { return }'],
+ [ios + 'ErrorRecovery.swift',
+ ' errorRecoveryQueue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(remoteLoadTimeout)) {',
+ ' errorRecoveryQueue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(remoteLoadTimeout)) {\n' +
+ ' guard self.cindyActive else { return }'],
+ [ios + 'ErrorRecovery.swift',
+ ' errorRecoveryQueue.asyncAfter(deadline: DispatchTime.now() + .seconds(10)) {',
+ ' errorRecoveryQueue.asyncAfter(deadline: DispatchTime.now() + .seconds(10)) {\n' +
+ ' guard self.cindyActive else { return }'],
+ [ios + 'ErrorRecovery.swift',
+ ' delegate?.markSuccessfulLaunchForLaunchedUpdate()\n errorRecoveryQueue.async {\n guard self.cindyActive else { return }',
+ ' errorRecoveryQueue.async {\n guard self.cindyActive else { return }\n' +
+ ' self.delegate?.markSuccessfulLaunchForLaunchedUpdate()'],
+ [ios + 'ErrorRecovery.swift',
+ ' if previousFatalErrorHandler != nil || previousFatalExceptionHandler != nil {\n return\n }',
+ ' if cindyInstalledHandlers { return }\n cindyInstalledHandlers = true'],
+ [ios + 'ErrorRecovery.swift',
+ ' private func unsetRCTErrorHandlers() {',
+ ' private func unsetRCTErrorHandlers() {\n' +
+ ' guard cindyInstalledHandlers else { return }\n cindyInstalledHandlers = false'],
+ [ios + 'Procedures/StartupProcedure.swift',
+ ' func markFailedLaunchForLaunchedUpdate() {\n if emergencyLaunchException != nil {\n return\n }',
+ ' func markFailedLaunchForLaunchedUpdate() {\n if emergencyLaunchException != nil {\n return\n }\n' +
+ ' CindyOtaJournal.failed(launchedUpdate())'],
+ [ios + 'Procedures/StartupProcedure.swift',
+ ' func markSuccessfulLaunchForLaunchedUpdate() {\n if emergencyLaunchException != nil {\n return\n }',
+ ' func markSuccessfulLaunchForLaunchedUpdate() {\n if emergencyLaunchException != nil {\n return\n }\n' +
+ ' if let update = launchedUpdate() { CindyOtaJournal.confirmed(update) }'],
+ [ios + 'AppLauncher/AppLauncherWithDatabase.swift',
+ ' self.completion = completion\n',
+ ' self.completion = { [weak self] error, success in\n' +
+ ' guard let self else { completion(error, success); return }\n' +
+ ' if !success && CindyOtaJournal.failed(self.launchedUpdate) {\n' +
+ ' self.completion = nil\n self.launchedUpdate = nil\n self.launchAssetUrl = nil\n' +
+ ' self.launchAssetError = nil\n self.assetFilesMap = nil\n self.completedAssets = 0\n' +
+ ' self.launchedFromEmbeddedBundle = false\n' +
+ ' self.launchUpdate(withSelectionPolicy: selectionPolicy, completion: completion)\n' +
+ ' } else { completion(error, success) }\n }\n'],
+ [ios + 'AppLauncher/AppLauncherWithDatabase.swift',
+ ' private func finishLaunch() {\n markUpdateAccessed()',
+ ' private func finishLaunch() {\n' +
+ ' if let update = launchedUpdate {\n' +
+ ' do { try CindyOtaJournal.selected(update) } catch {\n' +
+ ' let callback = self.completion\n self.completion = nil\n' +
+ ' callback?(UpdatesError.appLauncherNoLaunchableUpdates(cause: error), false)\n return\n }\n }\n' +
+ ' markUpdateAccessed()'],
+ [ios + 'AppLauncher/AppLauncherWithDatabase.swift',
+ 'self.completion!(self.launchAssetError, self.launchAssetUrl != nil)\n self.completion = nil',
+ 'let callback = self.completion\n self.completion = nil\n callback?(self.launchAssetError, self.launchAssetUrl != nil)'],
+ [ios + 'AppLauncher/AppLauncherWithDatabase.swift',
+ 'self.completion!(self.launchAssetError, self.launchAssetUrl != nil)\n self.completion = nil',
+ 'let callback = self.completion\n self.completion = nil\n callback?(self.launchAssetError, self.launchAssetUrl != nil)'],
+ // Never silently select an unmodified prebuilt framework over the adapter.
+ ['ios/EXUpdates.podspec',
+ ' if !ex_updates_native_debug && !$ExpoUseSources&.include?(package[\'name\'])',
+ ' if false && !ex_updates_native_debug && !$ExpoUseSources&.include?(package[\'name\'])'],
+ ];
+}
+
+function replaceChecked(source, before, after, label, expected = 1) {
+ if (source.split(before).length !== expected + 1) {
+ throw new Error('Self-host OTA adapter anchor mismatch: ' + label);
+ }
+ return source.split(before).join(after);
+}
+
+function patchSources(readSource) {
+ const result = new Map();
+ for (const [file, before, after, expected] of patches()) {
+ result.set(file, replaceChecked(result.get(file) ?? readSource(file), before, after, file, expected));
+ }
+ return result;
+}
+
+module.exports = { patchSources, replaceChecked, patches };
diff --git a/apps/mobile/plugins/with-selfhost-ota.js b/apps/mobile/plugins/with-selfhost-ota.js
new file mode 100644
index 0000000000..5d3a2fa15c
--- /dev/null
+++ b/apps/mobile/plugins/with-selfhost-ota.js
@@ -0,0 +1,99 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const { withDangerousMod, withPodfile, withSettingsGradle } = require('@expo/config-plugins');
+const { EXPO_UPDATES_VERSION, nativeSourceHash } = require('./selfhost-ota/contract');
+const { patchSources, replaceChecked } = require('./selfhost-ota/patches');
+
+const DIRECTORY = 'cindy-selfhost-expo-updates';
+const OWNER_FILE = '.cindy-selfhost-ota-adapter';
+const MARKER = 'cindy-selfhost-native-ota-v1';
+
+function resolveSources(projectRoot) {
+ const packageFile = require.resolve('expo-updates/package.json', { paths: [projectRoot] });
+ const packageRoot = fs.realpathSync(path.dirname(packageFile));
+ const version = JSON.parse(fs.readFileSync(packageFile, 'utf8')).version;
+ if (version !== EXPO_UPDATES_VERSION) {
+ throw new Error('Self-host OTA adapter requires expo-updates@' + EXPO_UPDATES_VERSION + '; review the native hooks before upgrading');
+ }
+ const patched = patchSources((file) => fs.readFileSync(path.join(packageRoot, file), 'utf8'));
+ return { packageRoot, patched };
+}
+
+function prepareAdapter(projectRoot, platformRoot) {
+ // Validate all upstream hooks before touching any generated output. The
+ // original dependency is read-only, even across simultaneous EAS/self-host builds.
+ const { packageRoot, patched } = resolveSources(projectRoot);
+ const parent = fs.realpathSync(platformRoot);
+ const destination = path.join(parent, DIRECTORY);
+ if (fs.existsSync(destination)) {
+ if (fs.lstatSync(destination).isSymbolicLink() ||
+ fs.readFileSync(path.join(destination, OWNER_FILE), 'utf8') !== MARKER) {
+ throw new Error('Refusing to replace an unowned self-host OTA adapter directory');
+ }
+ // This fixed child is exclusively generated by this plugin; it never holds
+ // credentials, user data or shared dependencies.
+ fs.rmSync(destination, { recursive: true });
+ }
+ fs.cpSync(packageRoot, destination, {
+ recursive: true,
+ dereference: true,
+ filter: (entry) => {
+ const parts = path.relative(packageRoot, entry).split(path.sep);
+ return !parts.some((part) => part === 'node_modules' || part === '.git' ||
+ part === '.gradle' || part.endsWith('.xcframework')) &&
+ !(parts[0] === 'android' && parts[1] === 'build');
+ },
+ });
+ for (const [file, source] of patched) fs.writeFileSync(path.join(destination, file), source);
+ fs.copyFileSync(path.join(__dirname, 'selfhost-ota/android/CindyOtaJournal.kt'),
+ path.join(destination, 'android/src/main/java/expo/modules/updates/CindyOtaJournal.kt'));
+ fs.copyFileSync(path.join(__dirname, 'selfhost-ota/ios/CindyOtaJournal.swift'),
+ path.join(destination, 'ios/EXUpdates/CindyOtaJournal.swift'));
+ fs.writeFileSync(path.join(destination, OWNER_FILE), MARKER);
+ return destination;
+}
+
+function patchPodfile(source) {
+ if (source.includes('# ' + MARKER)) return source;
+ return replaceChecked(source, ' use_expo_modules!',
+ ' # ' + MARKER + '\n' +
+ " pod 'EXUpdates', :path => './" + DIRECTORY + "/ios', :modular_headers => true\n" +
+ ' use_expo_modules!', 'Podfile');
+}
+
+function patchSettingsGradle(source) {
+ if (source.includes('// ' + MARKER)) return source;
+ if (!source.includes('expoAutolinking.useExpoModules()')) {
+ throw new Error('Self-host OTA adapter requires the Expo settings autolinking hook');
+ }
+ return source + '\n// ' + MARKER + '\n' +
+ "project(':expo-updates').projectDir = new File(rootDir, '" + DIRECTORY + "/android')\n";
+}
+
+function withSelfhostOta(config, options = {}) {
+ if (process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST !== '1' || process.env.CINDY_MOBILE_OTA_NATIVE !== '1') {
+ throw new Error('Native OTA adapter may only be assembled by an explicitly enabled self-host build');
+ }
+ if (options.sourceHash !== nativeSourceHash()) {
+ throw new Error('Native OTA adapter sources do not match the resolved runtime fingerprint inputs');
+ }
+ for (const platform of ['android', 'ios']) {
+ config = withDangerousMod(config, [platform, async (mod) => {
+ prepareAdapter(mod.modRequest.projectRoot, mod.modRequest.platformProjectRoot);
+ return mod;
+ }]);
+ }
+ config = withPodfile(config, (mod) => {
+ mod.modResults.contents = patchPodfile(mod.modResults.contents);
+ return mod;
+ });
+ config = withSettingsGradle(config, (mod) => {
+ if (mod.modResults.language !== 'groovy') throw new Error('Unsupported Android settings language for self-host OTA');
+ mod.modResults.contents = patchSettingsGradle(mod.modResults.contents);
+ return mod;
+ });
+ return config;
+}
+
+module.exports = withSelfhostOta;
+module.exports.__testing = { resolveSources, prepareAdapter, patchPodfile, patchSettingsGradle };
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/AtomicFile.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/AtomicFile.kt
new file mode 100644
index 0000000000..bf9dccc451
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/AtomicFile.kt
@@ -0,0 +1,23 @@
+package android.util
+
+import java.io.File
+import java.io.FileOutputStream
+
+// Boundary double only; the actual journal serializes/validates its own state
+// and performs real temporary-file writes, fsync and rename in these tests.
+class AtomicFile(private val file: File) {
+ private val pending = File(file.path + ".new")
+ fun readFully(): ByteArray = file.readBytes()
+ fun startWrite(): FileOutputStream {
+ file.parentFile.mkdirs()
+ return FileOutputStream(pending)
+ }
+ fun finishWrite(stream: FileOutputStream) {
+ stream.close()
+ check(pending.renameTo(file))
+ }
+ fun failWrite(stream: FileOutputStream) { stream.close(); pending.delete() }
+}
+object Log {
+ fun w(tag: String, message: String): Int { println("[$tag] $message"); return 0 }
+}
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/Context.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/Context.kt
new file mode 100644
index 0000000000..c43b23de66
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/Context.kt
@@ -0,0 +1,27 @@
+package android.content
+
+import java.io.File
+
+class Context(val noBackupFilesDir: File) {
+ companion object { const val MODE_PRIVATE = 0 }
+ val applicationContext: Context get() = this
+ val preferences = Preferences()
+ fun getSharedPreferences(name: String, mode: Int) = preferences
+}
+class Preferences {
+ val strings = mutableMapOf<String, String>()
+ var writable = true
+ fun edit() = Editor(this)
+}
+class Editor(private val preferences: Preferences) {
+ private val mutations = mutableMapOf<String, String?>()
+ fun remove(key: String): Editor { mutations[key] = null; return this }
+ fun putString(key: String, value: String): Editor { mutations[key] = value; return this }
+ fun commit(): Boolean {
+ if (!preferences.writable) return false
+ for ((key, value) in mutations) {
+ if (value == null) preferences.strings.remove(key) else preferences.strings[key] = value
+ }
+ return true
+ }
+}
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/ExpoBoundary.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/ExpoBoundary.kt
new file mode 100644
index 0000000000..9b0c917ac7
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/ExpoBoundary.kt
@@ -0,0 +1,33 @@
+package expo.modules.updates
+
+import android.content.Context
+import org.json.JSONObject
+import java.net.URI
+
+class UpdatesConfiguration {
+ companion object {
+ var fixtureRuntime = "r1"
+ fun create(context: Context, config: UpdatesConfiguration, configOverride: UpdatesConfigurationOverride?): UpdatesConfiguration =
+ UpdatesConfiguration(context, null, false, configOverride)
+ }
+ val updateUrl = URI("https://updates.example.invalid/manifest")
+ val scopeKey = "https://updates.example.invalid"
+ val originalEmbeddedRequestHeaders = mapOf("EAS-Client-ID" to "00000000-0000-4000-8000-000000000000", "x-cindy-update-channel" to "")
+ val disableAntiBrickingMeasures = false
+ private val nativeRuntime = fixtureRuntime
+ val requestHeaders: Map<String, String>
+ constructor(context: Context, overrideMap: Map<String, Any>?, disableAntiBrickingMeasures: Boolean, configOverride: UpdatesConfigurationOverride?) {
+ requestHeaders = configOverride?.requestHeaders ?: originalEmbeddedRequestHeaders
+ }
+ fun getRuntimeVersion() = nativeRuntime
+}
+data class UpdatesConfigurationOverride(val updateUrl: URI?, val requestHeaders: Map<String, String>?)
+class FixtureController {
+ lateinit var context: Context
+ var lastHeaders: Map<String, String>? = null
+ fun setUpdateRequestHeadersOverride(headers: Map<String, String>?) {
+ lastHeaders = headers
+ context.preferences.strings["updatesConfigOverride"] = JSONObject().put("requestHeaders", JSONObject(headers)).toString()
+ }
+}
+object UpdatesController { val instance = FixtureController() }
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/JournalFixture.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/JournalFixture.kt
new file mode 100644
index 0000000000..a7e858b285
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/JournalFixture.kt
@@ -0,0 +1,136 @@
+package expo.modules.updates
+
+import android.content.Context
+import expo.modules.updates.db.entity.UpdateEntity
+import expo.modules.updates.db.enums.UpdateStatus
+import java.io.File
+import java.util.Date
+import java.util.UUID
+
+fun main(args: Array<String>) {
+ val root = File(args[0])
+ val context = Context(File(root, "journal-cases"))
+ UpdatesController.instance.context = context
+ fun config(channel: String = "release") = UpdatesConfiguration(context, null, false,
+ UpdatesConfigurationOverride(null, CindyOtaJournal.headers(channel)))
+ fun update(sequence: Int, channel: String = "release", embedded: Boolean = false): UpdateEntity = UpdateEntity(
+ UUID.fromString("00000000-0000-4000-8000-" + sequence.toString().padStart(12, '0')),
+ UpdatesConfiguration.fixtureRuntime, config().scopeKey,
+ if (embedded) UpdateStatus.EMBEDDED else UpdateStatus.READY,
+ config().updateUrl, CindyOtaJournal.headers(if (embedded) "release" else channel), Date(sequence.toLong())
+ )
+ fun selected(vararg updates: UpdateEntity) = CindyOtaJournal.select(updates.toList(), config())?.update
+ fun fetch(update: UpdateEntity, channel: String): String {
+ val token = CindyOtaJournal.begin(channel)
+ CindyOtaJournal.downloaded(update, config(channel))
+ return token
+ }
+ val embedded = update(1, embedded = true)
+ val release = update(2)
+ val beta = update(3, "beta")
+ val canary = update(4, "canary")
+ val unrelated = update(5)
+ var binary = embedded
+ fun reboot() {
+ CindyOtaJournal.prepare(context)
+ CindyOtaJournal.observeEmbedded(binary)
+ }
+ CindyOtaJournal.validateHeaders(null)
+ check(runCatching { CindyOtaJournal.validateHeaders(mapOf("x-cindy-update-channel" to "beta")) }.isFailure)
+
+ context.preferences.strings["updatesConfigOverride"] = "legacy malformed override"
+ reboot()
+ check(!context.preferences.strings.containsKey("updatesConfigOverride"))
+ check(selected(embedded, unrelated) === embedded)
+ CindyOtaJournal.confirmed(embedded)
+ CindyOtaJournal.finish(fetch(release, "release"))
+ CindyOtaJournal.selected(release)
+ CindyOtaJournal.confirmed(release)
+ check(CindyOtaJournal.pinned(release.id) && !CindyOtaJournal.pinned(unrelated.id))
+
+ CindyOtaJournal.begin("beta")
+ reboot()
+ check(selected(embedded, release, beta) === release)
+ check(CindyOtaJournal.currentHeaders() == CindyOtaJournal.headers("release"))
+ fetch(beta, "beta")
+ reboot()
+ check(selected(embedded, release, beta) === beta)
+ check(CindyOtaJournal.pinned(release.id) && CindyOtaJournal.pinned(beta.id))
+ CindyOtaJournal.selected(beta)
+ CindyOtaJournal.finish(fetch(beta, "beta"))
+ reboot()
+ check(selected(embedded, release, beta) === beta)
+ CindyOtaJournal.selected(beta)
+ reboot()
+ check(selected(embedded, release, beta) === release)
+ check(!CindyOtaJournal.pinned(beta.id))
+
+ CindyOtaJournal.finish(fetch(canary, "canary"))
+ CindyOtaJournal.selected(canary)
+ check(CindyOtaJournal.failed(canary))
+ check(selected(embedded, release, canary) === release)
+ check(UpdatesController.instance.lastHeaders == CindyOtaJournal.headers("release"))
+ val nextBeta = update(6, "beta")
+ CindyOtaJournal.finish(fetch(nextBeta, "beta"))
+ CindyOtaJournal.selected(nextBeta)
+ CindyOtaJournal.confirmed(nextBeta)
+ check(!CindyOtaJournal.failed(nextBeta))
+ reboot()
+ check(selected(embedded, release, nextBeta) === nextBeta)
+ check(!CindyOtaJournal.pinned(release.id))
+ CindyOtaJournal.rolledBackToEmbedded()
+ check(selected(embedded, nextBeta) === embedded)
+
+ // Expo reuses the DB download identity when an identical ID moves channels.
+ val promoted = update(8, "beta")
+ val promoteToken = CindyOtaJournal.begin("release")
+ CindyOtaJournal.downloaded(promoted, config("release"))
+ CindyOtaJournal.finish(promoteToken)
+ check(selected(embedded, promoted) === promoted)
+ CindyOtaJournal.confirmed(promoted)
+ val olderBinary = update(7, embedded = true)
+ binary = olderBinary
+ reboot()
+ check(selected(embedded, olderBinary, promoted) === promoted)
+ val equalBinary = update(9, embedded = true).copy(commitTime = promoted.commitTime)
+ binary = equalBinary
+ reboot()
+ check(selected(equalBinary, promoted) === promoted)
+ val newerBinary = update(10, embedded = true)
+ binary = newerBinary
+ reboot()
+ check(selected(embedded, newerBinary, promoted) === newerBinary)
+ check(!CindyOtaJournal.pinned(promoted.id))
+ CindyOtaJournal.confirmed(newerBinary)
+ // A deliberately requested older channel after installation is not pruned on
+ // every boot; only an actual change to the binary identity triggers pruning.
+ val explicitOlder = update(6, "release")
+ CindyOtaJournal.finish(fetch(explicitOlder, "release"))
+ reboot()
+ check(selected(newerBinary, explicitOlder) === explicitOlder)
+ CindyOtaJournal.confirmed(explicitOlder)
+ val newerPending = update(12, "beta")
+ CindyOtaJournal.finish(fetch(newerPending, "beta"))
+ val nextBinary = update(11, embedded = true)
+ binary = nextBinary
+ reboot()
+ check(selected(nextBinary, newerPending) === newerPending)
+ check(CindyOtaJournal.failed(newerPending))
+ check(selected(newerBinary, nextBinary, newerPending) === nextBinary)
+
+ UpdatesConfiguration.fixtureRuntime = "r2"
+ val embedded2 = update(7, embedded = true)
+ binary = embedded2
+ reboot()
+ check(selected(embedded2, release) === embedded2)
+ check(!CindyOtaJournal.pinned(nextBeta.id))
+ val notDirectory = File(root, "not-a-directory").apply { writeText("fixture") }
+ val unavailable = Context(notDirectory)
+ unavailable.preferences.writable = false
+ CindyOtaJournal.prepare(unavailable)
+ CindyOtaJournal.observeEmbedded(embedded2)
+ check(CindyOtaJournal.capabilities()["available"] == false)
+ check(selected(embedded2, update(15)) === embedded2)
+ check(runCatching { CindyOtaJournal.begin("release") }.isFailure)
+ println("PASS: Android journal migration, kill windows, pending retry, same-process rollback, pinning, runtime and I/O cases")
+}
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateEntity.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateEntity.kt
new file mode 100644
index 0000000000..3416d56d26
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateEntity.kt
@@ -0,0 +1,18 @@
+package expo.modules.updates.db.entity
+
+import expo.modules.updates.db.enums.UpdateStatus
+import java.net.URI
+import java.util.Date
+import java.util.UUID
+
+data class UpdateEntity(
+ val id: UUID,
+ val runtimeVersion: String,
+ val scopeKey: String,
+ val status: UpdateStatus,
+ val url: URI?,
+ val requestHeaders: Map<String, String>?,
+ val commitTime: Date,
+ var successfulLaunchCount: Int = 0,
+ var failedLaunchCount: Int = 0
+)
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateStatus.kt b/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateStatus.kt
new file mode 100644
index 0000000000..0b80b82389
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-android/UpdateStatus.kt
@@ -0,0 +1,2 @@
+package expo.modules.updates.db.enums
+enum class UpdateStatus { READY, EMBEDDED, DEVELOPMENT }
diff --git a/apps/mobile/scripts/fixtures/selfhost-ota-journal.swift b/apps/mobile/scripts/fixtures/selfhost-ota-journal.swift
new file mode 100644
index 0000000000..30afd742a5
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/selfhost-ota-journal.swift
@@ -0,0 +1,205 @@
+// Native state-machine fixture: compile the PRODUCTION journal alongside these
+// narrow Expo boundary doubles. All filesystem writes stay in the supplied temp
+// directory. No simulator, account, real UserDefaults or application data is used.
+import Foundation
+
+enum UpdateStatus { case StatusReady, StatusEmbedded }
+struct UpdatesConfig {
+ let runtimeVersion: String
+ let updateUrl = URL(string: "https://updates.example.invalid/manifest")!
+ let scopeKey = "https://updates.example.invalid"
+ let disableAntiBrickingMeasures = false
+ let originalEmbeddedRequestHeaders = ["EAS-Client-ID": "00000000-0000-4000-8000-000000000000",
+ "x-cindy-update-channel": ""]
+ var requestHeaders: [String: String]
+ init(runtime: String = "r1", channel: String = "release") {
+ runtimeVersion = runtime
+ requestHeaders = try! CindyOtaJournal.headers(channel)
+ }
+ static var fixture = UpdatesConfig()
+ static func cindyEmbeddedConfiguration() throws -> UpdatesConfig { fixture }
+ static func config(fromConfig config: UpdatesConfig, configOverride: UpdatesConfigOverride?) throws -> UpdatesConfig {
+ var result = config
+ result.requestHeaders = configOverride?.requestHeaders ?? config.originalEmbeddedRequestHeaders
+ return result
+ }
+}
+struct UpdatesConfigOverride {
+ let updateUrl: URL?
+ let requestHeaders: [String: String]?
+ static var saved: UpdatesConfigOverride?
+ static func save(configOverride: UpdatesConfigOverride?) { saved = configOverride }
+}
+final class Update {
+ let updateId: UUID
+ let runtimeVersion: String
+ let scopeKey: String
+ let commitTime: Date
+ let status: UpdateStatus
+ let url: URL?
+ let requestHeaders: [String: String]?
+ var failedLaunchCount = 0
+ var successfulLaunchCount = 0
+ init(_ sequence: Int, channel: String = "release", embedded: Bool = false, runtime: String = "r1", time: Int? = nil) {
+ updateId = UUID(uuidString: String(format: "00000000-0000-4000-8000-%012d", sequence))!
+ runtimeVersion = runtime
+ scopeKey = UpdatesConfig.fixture.scopeKey
+ commitTime = Date(timeIntervalSince1970: Double(time ?? sequence))
+ status = embedded ? .StatusEmbedded : .StatusReady
+ url = UpdatesConfig.fixture.updateUrl
+ requestHeaders = try! CindyOtaJournal.headers(embedded ? "release" : channel)
+ }
+}
+final class FixtureController {
+ var lastHeaders: [String: String]?
+ func setUpdateRequestHeadersOverride(_ headers: [String: String]?) throws {
+ lastHeaders = headers
+ UpdatesConfigOverride.save(configOverride: UpdatesConfigOverride(updateUrl: nil, requestHeaders: headers))
+ }
+}
+enum AppController { static let sharedInstance = FixtureController() }
+
+@main
+struct JournalTests {
+ static func expect(_ condition: Bool, _ label: String) {
+ guard condition else { fatalError("FAILED: " + label) }
+ }
+ static func main() throws {
+ let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
+ let directory = root.appendingPathComponent("journal-cases", isDirectory: true)
+ let embedded = Update(1, embedded: true)
+ let release = Update(2)
+ let beta = Update(3, channel: "beta")
+ let canary = Update(4, channel: "canary")
+ let unrelated = Update(5)
+ let defaults = UpdatesConfig.fixture
+ try CindyOtaJournal.validateHeaders(nil)
+ do {
+ try CindyOtaJournal.validateHeaders(["x-cindy-update-channel": "beta"])
+ fatalError("FAILED: missing shared ID was accepted")
+ } catch {}
+ var binary = embedded
+ func reboot() throws {
+ try CindyOtaJournal.prepare(storageDirectoryForTesting: directory)
+ CindyOtaJournal.observeEmbedded(binary)
+ }
+ func selected(_ list: [Update]) -> Update? { CindyOtaJournal.select(list, config: defaults)?.update }
+ func fetch(_ update: Update, channel: String) throws -> String {
+ let token = try CindyOtaJournal.begin(channel)
+ try CindyOtaJournal.downloaded(update, config: UpdatesConfig(channel: channel))
+ return token
+ }
+
+ // Fresh binary migration removes the entire old override, not only its URL.
+ UpdatesConfigOverride.saved = UpdatesConfigOverride(updateUrl: URL(string: "https://legacy.example.invalid"), requestHeaders: [:])
+ try reboot()
+ expect(UpdatesConfigOverride.saved == nil, "old complete override removed")
+ expect(selected([embedded, unrelated]) === embedded, "unrecorded cached OTA is not adopted")
+ CindyOtaJournal.confirmed(embedded)
+ let releaseToken = try fetch(release, channel: "release")
+ try CindyOtaJournal.finish(releaseToken)
+ try CindyOtaJournal.selected(release)
+ CindyOtaJournal.confirmed(release)
+ expect(CindyOtaJournal.pinned(release.updateId), "successful release resources are pinned")
+ expect(!CindyOtaJournal.pinned(unrelated.updateId), "pin is an explicit allowlist")
+
+ // Process death after changing headers but before a completed download.
+ _ = try CindyOtaJournal.begin("beta")
+ try reboot()
+ expect(selected([embedded, release, beta]) === release, "interrupted request restores release")
+ expect(try CindyOtaJournal.currentHeaders() == CindyOtaJournal.headers("release"), "restored canonical release headers")
+
+ // Native download commit survives destruction before the JS callback/finally.
+ _ = try fetch(beta, channel: "beta")
+ try reboot()
+ expect(selected([embedded, release, beta]) === beta, "downloaded candidate survives killed JS")
+ expect(CindyOtaJournal.pinned(release.updateId) && CindyOtaJournal.pinned(beta.updateId), "old and pending assets survive reaping")
+ try CindyOtaJournal.selected(beta)
+ // Refetching a cached ID must not reset its launch attempts.
+ let betaToken = try fetch(beta, channel: "beta")
+ try CindyOtaJournal.finish(betaToken)
+ try reboot()
+ expect(selected([embedded, release, beta]) === beta, "one bounded retry remains")
+ try CindyOtaJournal.selected(beta)
+ try reboot()
+ expect(selected([embedded, release, beta]) === release, "two unconfirmed launches restore known-good")
+ expect(!CindyOtaJournal.pinned(beta.updateId), "rejected candidate is unpinned")
+
+ // An in-process pre-content error must repair state/config before relaunch.
+ let canaryToken = try fetch(canary, channel: "canary")
+ try CindyOtaJournal.finish(canaryToken)
+ try CindyOtaJournal.selected(canary)
+ expect(CindyOtaJournal.failed(canary), "pending native failure is handled")
+ expect(selected([embedded, release, canary]) === release, "same-process rollback chooses release")
+ expect(AppController.sharedInstance.lastHeaders == (try CindyOtaJournal.headers("release")), "same-process config repaired")
+
+ let nextBeta = Update(6, channel: "beta")
+ let nextToken = try fetch(nextBeta, channel: "beta")
+ try CindyOtaJournal.finish(nextToken)
+ try CindyOtaJournal.selected(nextBeta)
+ CindyOtaJournal.confirmed(nextBeta)
+ expect(!CindyOtaJournal.failed(nextBeta), "never auto-rollback after content appeared")
+ try reboot()
+ expect(selected([embedded, release, nextBeta]) === nextBeta, "successful candidate is the next baseline")
+ expect(!CindyOtaJournal.pinned(release.updateId), "superseded good is not pinned forever")
+ try CindyOtaJournal.rolledBackToEmbedded()
+ expect(selected([embedded, nextBeta]) === embedded, "accepted Expo rollback directive wins over journal")
+
+ let promoted = Update(8, channel: "beta")
+ let promoteToken = try CindyOtaJournal.begin("release")
+ try CindyOtaJournal.downloaded(promoted, config: UpdatesConfig(channel: "release"))
+ try CindyOtaJournal.finish(promoteToken)
+ expect(selected([embedded, promoted]) === promoted, "cached ID uses the DB identity, not the new response headers")
+ CindyOtaJournal.confirmed(promoted)
+ let olderBinary = Update(7, embedded: true)
+ binary = olderBinary
+ try reboot()
+ expect(selected([embedded, olderBinary, promoted]) === promoted, "newer OTA survives older same-runtime binary")
+ let equalBinary = Update(9, embedded: true, time: 8)
+ binary = equalBinary
+ try reboot()
+ expect(selected([equalBinary, promoted]) === promoted, "equal timestamp OTA survives binary replacement")
+ let newerBinary = Update(10, embedded: true)
+ binary = newerBinary
+ try reboot()
+ expect(selected([embedded, newerBinary, promoted]) === newerBinary, "newer binary is not hidden by old good OTA")
+ expect(!CindyOtaJournal.pinned(promoted.updateId), "older OTA no longer pins after binary replacement")
+ CindyOtaJournal.confirmed(newerBinary)
+ let explicitOlder = Update(6)
+ try CindyOtaJournal.finish(fetch(explicitOlder, channel: "release"))
+ try reboot()
+ expect(selected([newerBinary, explicitOlder]) === explicitOlder, "normal boot does not impose a new embedded floor")
+ CindyOtaJournal.confirmed(explicitOlder)
+ let newerPending = Update(12, channel: "beta")
+ try CindyOtaJournal.finish(fetch(newerPending, channel: "beta"))
+ let nextBinary = Update(11, embedded: true)
+ binary = nextBinary
+ try reboot()
+ expect(selected([nextBinary, newerPending]) === newerPending, "newer pending is retained across binary replacement")
+ expect(CindyOtaJournal.failed(newerPending), "retained candidate can fail")
+ expect(selected([newerBinary, nextBinary, newerPending]) === nextBinary, "failed retained OTA falls back to this binary only")
+
+ // Native runtime change invalidates receipts; it does not try to run an old OTA.
+ UpdatesConfig.fixture = UpdatesConfig(runtime: "r2")
+ let embedded2 = Update(7, embedded: true, runtime: "r2")
+ binary = embedded2
+ try reboot()
+ expect(CindyOtaJournal.select([embedded2, release], config: UpdatesConfig.fixture)?.update === embedded2,
+ "new runtime starts its new embedded bundle")
+ expect(!CindyOtaJournal.pinned(nextBeta.updateId), "old runtime pin removed")
+
+ // An unavailable auxiliary store disables OTA, not the app or user data.
+ let notDirectory = root.appendingPathComponent("not-a-directory")
+ try Data("fixture".utf8).write(to: notDirectory)
+ try CindyOtaJournal.prepare(storageDirectoryForTesting: notDirectory)
+ CindyOtaJournal.observeEmbedded(embedded2)
+ expect(CindyOtaJournal.capabilities()["available"] as? Bool == false, "I/O failure disables the adapter")
+ expect(CindyOtaJournal.select([embedded2, Update(15, runtime: "r2")], config: UpdatesConfig.fixture)?.update === embedded2,
+ "unavailable journal cannot adopt unrecorded release cache")
+ do {
+ _ = try CindyOtaJournal.begin("release")
+ fatalError("FAILED: unavailable journal admitted a request")
+ } catch {}
+ print("PASS: native journal migration, kill windows, pending retry, same-process rollback, pinning, runtime and I/O cases")
+ }
+}
diff --git a/apps/mobile/scripts/test-selfhost-ota-android.mjs b/apps/mobile/scripts/test-selfhost-ota-android.mjs
new file mode 100644
index 0000000000..df118a2cef
--- /dev/null
+++ b/apps/mobile/scripts/test-selfhost-ota-android.mjs
@@ -0,0 +1,25 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const mobile = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const compiler = process.env.CINDY_OTA_TEST_KOTLINC;
+const jdk = process.env.CINDY_OTA_TEST_JDK_HOME;
+const json = process.env.CINDY_OTA_TEST_JSON_JAR;
+if (!compiler || !jdk || !json) throw new Error('Provide CINDY_OTA_TEST_KOTLINC, CINDY_OTA_TEST_JDK_HOME and CINDY_OTA_TEST_JSON_JAR');
+const directory = mkdtempSync(join(tmpdir(), 'cindy-android-ota-test-'));
+try {
+ const fixtures = join(mobile, 'scripts/fixtures/selfhost-ota-android');
+ const jar = join(directory, 'journal.jar');
+ execFileSync(compiler, [
+ join(mobile, 'plugins/selfhost-ota/android/CindyOtaJournal.kt'),
+ ...readdirSync(fixtures).filter((file) => file.endsWith('.kt')).map((file) => join(fixtures, file)),
+ '-cp', json, '-include-runtime', '-d', jar,
+ ], { env: { ...process.env, JAVA_HOME: jdk }, stdio: 'inherit' });
+ execFileSync(join(jdk, 'bin/java'), ['-cp', jar + delimiter + json, 'expo.modules.updates.JournalFixtureKt', directory], { stdio: 'inherit' });
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/apps/mobile/scripts/test-selfhost-ota-native.mjs b/apps/mobile/scripts/test-selfhost-ota-native.mjs
new file mode 100644
index 0000000000..765e00aa69
--- /dev/null
+++ b/apps/mobile/scripts/test-selfhost-ota-native.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const mobile = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(import.meta.url);
+const { patchSources } = require('../plugins/selfhost-ota/patches');
+const expo = dirname(require.resolve('expo-updates/package.json'));
+const directory = mkdtempSync(join(tmpdir(), 'cindy-native-ota-test-'));
+try {
+ const executable = join(directory, 'journal-tests');
+ execFileSync('swiftc', [
+ join(mobile, 'plugins/selfhost-ota/ios/CindyOtaJournal.swift'),
+ join(mobile, 'scripts/fixtures/selfhost-ota-journal.swift'), '-o', executable,
+ ], { stdio: 'inherit' });
+ execFileSync(executable, [directory], { stdio: 'inherit' });
+ for (const [file, source] of patchSources((file) => readFileSync(join(expo, file), 'utf8'))) {
+ if (!file.endsWith('.swift')) continue;
+ const temporarySource = join(directory, file.split('/').pop());
+ writeFileSync(temporarySource, source);
+ execFileSync('swiftc', ['-parse', temporarySource], { stdio: 'inherit' });
+ }
+ console.log('PASS: all adapted Expo Swift sources parse');
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
index 4ec08bd38b..1c252fa85f 100644
--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts
+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
@@ -24,6 +24,8 @@ const managedEnvKeys = [
'EXPO_PUBLIC_CINDY_GOOGLE_IOS_URL_SCHEME',
'CINDY_USE_LOCAL_REGION_CONFIG',
'CINDY_SELF_HOST_REGIONS_FILE',
+ 'CINDY_MOBILE_OTA_NATIVE',
+ 'CINDY_MOBILE_UPDATES_URL',
];
let previousEnv: Record<string, string | undefined>;
const temporaryDirs: string[] = [];
@@ -249,6 +251,37 @@ describe('mobile native app config', () => {
]);
});
+ it('enables the native contract only for an explicitly opted-in self-host cold build', () => {
+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));
+ const config = JSON.parse(readFileSync(resolve(process.cwd(), 'app.json'), 'utf8')).expo;
+ const regular = buildConfig({ config });
+ const directory = mkdtempSync(join(tmpdir(), 'cindy-native-ota-regions-'));
+ temporaryDirs.push(directory);
+ process.env.CINDY_SELF_HOST_REGIONS_FILE = join(directory, 'regions.json');
+ writeFileSync(process.env.CINDY_SELF_HOST_REGIONS_FILE, JSON.stringify({ cn: {
+ iosBundleId: 'com.xd.cindycn', androidPackage: 'com.xd.cindycn',
+ tapdb: { clientId: 'test-id', clientToken: 'test-token' },
+ } }));
+ process.env.CINDY_MOBILE_OTA_NATIVE = '1';
+ // A stale self-host build variable cannot install a module into EAS.
+ expect(buildConfig({ config })).toEqual(regular);
+ process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST = '1';
+ expect(() => buildConfig({ config })).toThrow('CINDY_MOBILE_UPDATES_URL');
+ process.env.CINDY_MOBILE_UPDATES_URL = 'https://updates.example.invalid/root';
+ const native = buildConfig({ config });
+ expect(native.updates).toMatchObject({
+ url: 'https://updates.example.invalid/root/manifest', checkAutomatically: 'NEVER',
+ disableAntiBrickingMeasures: false,
+ requestHeaders: { 'EAS-Client-ID': '00000000-0000-4000-8000-000000000000', 'x-cindy-update-channel': '' },
+ });
+ expect(native.plugins).toContainEqual(['./plugins/with-selfhost-ota', { sourceHash: expect.stringMatching(/^[a-f0-9]{64}$/) }]);
+ process.env.CINDY_MOBILE_OTA_NATIVE = '0';
+ const legacy = buildConfig({ config });
+ expect(legacy.updates.url).toBe('https://selfhost.invalid/manifest');
+ expect(legacy.updates).not.toHaveProperty('requestHeaders');
+ expect(legacy.plugins).not.toContainEqual(expect.arrayContaining(['./plugins/with-selfhost-ota']));
+ });
+
it('keeps the existing EAS Google environment path outside self-host builds', () => {
const appJson = JSON.parse(
readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),
diff --git a/apps/mobile/src/__tests__/selfhostOtaPlugin.test.ts b/apps/mobile/src/__tests__/selfhostOtaPlugin.test.ts
new file mode 100644
index 0000000000..08e9f111dc
--- /dev/null
+++ b/apps/mobile/src/__tests__/selfhostOtaPlugin.test.ts
@@ -0,0 +1,80 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+const require = createRequire(import.meta.url);
+const contract = require('../../plugins/selfhost-ota/contract');
+const patcher = require('../../plugins/selfhost-ota/patches');
+const plugin = require('../../plugins/with-selfhost-ota').__testing;
+const directories: string[] = [];
+afterEach(() => { for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }); });
+
+describe('self-host native OTA build contract', () => {
+ it('uses one canonical header identity including release', () => {
+ expect(contract.requestHeaders()).toEqual({ 'EAS-Client-ID': '00000000-0000-4000-8000-000000000000',
+ 'x-cindy-update-channel': '' });
+ expect(contract.requestHeaders('beta')['x-cindy-update-channel']).toBe('beta');
+ expect(() => contract.requestHeaders('unknown')).toThrow();
+ });
+ it.each(['', 'http://updates.example.invalid', 'https://user:[email protected]',
+ 'https://updates.example.invalid?a=b', 'https://updates.example.invalid#hash'])('rejects unsafe build URL %s', (url) => {
+ expect(() => contract.resolveUpdatesUrl(url)).toThrow();
+ });
+ it('normalizes only the manifest suffix', () => {
+ expect(contract.resolveUpdatesUrl('https://updates.example.invalid/root/')).toBe('https://updates.example.invalid/root/manifest');
+ expect(contract.resolveUpdatesUrl('https://updates.example.invalid/root/manifest/')).toBe('https://updates.example.invalid/root/manifest');
+ });
+ it('includes both native implementations in the resolved fingerprint digest', () => {
+ const first = contract.nativeSourceHash((file: string) => file);
+ const second = contract.nativeSourceHash((file: string) => file.endsWith('.swift') ? file + ':changed' : file);
+ const third = contract.nativeSourceHash((file: string) => file.endsWith('.kt') ? file + ':changed' : file);
+ expect(first).not.toBe(second);
+ expect(first).not.toBe(third);
+ expect(contract.nativeSourceHash()).toMatch(/^[a-f0-9]{64}$/);
+ });
+ it('validates every pinned upstream hook and refuses ambiguous or missing anchors', () => {
+ const { patched } = plugin.resolveSources(process.cwd());
+ expect(patched.size).toBe(23);
+ expect(() => patcher.replaceChecked('a a', 'a', 'b', 'ambiguous')).toThrow('anchor mismatch');
+ expect(() => patcher.replaceChecked('x', 'a', 'b', 'missing')).toThrow('anchor mismatch');
+ expect(patcher.replaceChecked('a a', 'a', 'b', 'two audited hooks', 2)).toBe('b b');
+ const android = 'android/src/main/java/expo/modules/updates/';
+ expect(patched.get(android + 'loader/LoaderTask.kt')).toContain('.observeEmbedded(embeddedUpdate)');
+ expect(patched.get(android + 'procedures/FetchUpdateProcedure.kt')).toContain('loadUpdateWithId(availableUpdate.id)');
+ expect(patched.get('ios/EXUpdates/Procedures/FetchUpdateProcedure.swift')).toContain('self.database.update(withId: update.updateId');
+ expect(patched.get(android + 'errorrecovery/ErrorRecoveryHandler.kt')).toContain('if (cindyActive) super.dispatchMessage(msg)');
+ expect(patched.get('ios/EXUpdates/Procedures/StartupProcedure.swift')).toContain('errorRecovery.cindyRetire()');
+ });
+ it('assembles an isolated source dependency without changing shared node_modules', () => {
+ const directory = mkdtempSync(join(tmpdir(), 'cindy-ota-adapter-'));
+ directories.push(directory);
+ const { packageRoot, patched } = plugin.resolveSources(process.cwd());
+ const original = readFileSync(join(packageRoot, 'ios/EXUpdates/UpdatesModule.swift'), 'utf8');
+ const destination = plugin.prepareAdapter(process.cwd(), directory);
+ for (const [file, source] of patched) expect(readFileSync(join(destination, file), 'utf8')).toBe(source);
+ expect(readFileSync(join(destination, 'ios/EXUpdates/CindyOtaJournal.swift'), 'utf8')).toContain('maximumAttempts = 2');
+ expect(readFileSync(join(packageRoot, 'ios/EXUpdates/UpdatesModule.swift'), 'utf8')).toBe(original);
+ expect(plugin.prepareAdapter(process.cwd(), directory)).toBe(destination);
+ expect(readFileSync(join(packageRoot, 'ios/EXUpdates/UpdatesModule.swift'), 'utf8')).toBe(original);
+ }, 20_000);
+ it('does not overwrite an unrelated directory', () => {
+ const directory = mkdtempSync(join(tmpdir(), 'cindy-ota-unowned-'));
+ directories.push(directory);
+ const destination = join(directory, 'cindy-selfhost-expo-updates');
+ mkdirSync(destination);
+ writeFileSync(join(destination, 'user-file.txt'), 'keep');
+ expect(() => plugin.prepareAdapter(process.cwd(), directory)).toThrow();
+ expect(readFileSync(join(destination, 'user-file.txt'), 'utf8')).toBe('keep');
+ });
+ it('registers only the generated dependency and is idempotent', () => {
+ const podfile = "target 'Cindy' do\n use_expo_modules!\nend\n";
+ const modified = plugin.patchPodfile(podfile);
+ expect(modified.indexOf("pod 'EXUpdates'")).toBeLessThan(modified.indexOf('use_expo_modules!'));
+ expect(plugin.patchPodfile(modified)).toBe(modified);
+ const gradle = 'expoAutolinking.useExpoModules()\ninclude(":app")\n';
+ expect(plugin.patchSettingsGradle(gradle)).toContain("project(':expo-updates').projectDir");
+ expect(plugin.patchSettingsGradle(plugin.patchSettingsGradle(gradle))).toBe(plugin.patchSettingsGradle(gradle));
+ });
+});
diff --git a/apps/mobile/src/update/nativeOtaBridge.ts b/apps/mobile/src/update/nativeOtaBridge.ts
new file mode 100644
index 0000000000..62d61484b5
--- /dev/null
+++ b/apps/mobile/src/update/nativeOtaBridge.ts
@@ -0,0 +1,13 @@
+import { requireOptionalNativeModule } from 'expo-modules-core';
+import type { NativeOtaBridge } from './nativeOtaRequestCoordinator';
+
+/** Capability comes from the installed native binary, not the downloaded manifest. */
+export function getNativeOtaBridge(): NativeOtaBridge | null {
+ const module = requireOptionalNativeModule<Partial<NativeOtaBridge>>('ExpoUpdates');
+ if (typeof module?.cindySelfHostOtaCapabilities !== 'function') return null;
+ if (typeof module.cindyBeginSelfHostOtaRequest !== 'function' ||
+ typeof module.cindyFinishSelfHostOtaRequest !== 'function') {
+ throw new Error('incomplete-native-ota-contract');
+ }
+ return module as NativeOtaBridge;
+}
diff --git a/apps/mobile/src/update/nativeOtaRequestCoordinator.test.ts b/apps/mobile/src/update/nativeOtaRequestCoordinator.test.ts
new file mode 100644
index 0000000000..89e2a2f676
--- /dev/null
+++ b/apps/mobile/src/update/nativeOtaRequestCoordinator.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createNativeOtaRequestCoordinator, type NativeOtaBridge } from './nativeOtaRequestCoordinator';
+
+function harness() {
+ const events: string[] = [];
+ const bridge: NativeOtaBridge = {
+ cindySelfHostOtaCapabilities: vi.fn(() => ({ version: 1, runtimeVersion: 'native-r1',
+ updateUrl: 'https://native.example.invalid/manifest', available: true })),
+ cindyBeginSelfHostOtaRequest: vi.fn((channel) => { events.push('begin:' + channel); return 'token'; }),
+ cindyFinishSelfHostOtaRequest: vi.fn(() => { events.push('finish'); }),
+ };
+ const client = {
+ checkForUpdateAsync: vi.fn(async () => ({ isAvailable: true, manifest: { id: 'u2' } })),
+ fetchUpdateAsync: vi.fn(async () => ({ isNew: true, manifest: { id: 'u2' } })),
+ reloadAsync: vi.fn(async () => { events.push('reload'); }),
+ };
+ return { events, bridge, client, coordinator: createNativeOtaRequestCoordinator(bridge, client) };
+}
+const options = { channel: 'beta' as const, currentUpdateId: 'u1', runtimeVersion: 'native-r1' };
+afterEach(() => vi.useRealTimers());
+
+describe('native self-host OTA scheduling', () => {
+ it('uses the native contract and closes its request before destroying the JS runtime', async () => {
+ const h = harness();
+ await h.coordinator.run(options, async (client) => {
+ await client.checkForUpdateAsync();
+ await client.fetchUpdateAsync();
+ await client.reloadAsync();
+ });
+ expect(h.events).toEqual(['begin:beta', 'finish', 'reload']);
+ });
+
+ it.each([
+ { version: 2 }, { available: false }, { runtimeVersion: 'other-runtime' }, { updateUrl: '' },
+ ])('fails closed for a mismatched native contract: %j', async (override) => {
+ const h = harness();
+ const capability = h.bridge.cindySelfHostOtaCapabilities();
+ vi.mocked(h.bridge.cindySelfHostOtaCapabilities).mockReturnValue({ ...capability, ...override });
+ await expect(h.coordinator.run(options, (client) => client.checkForUpdateAsync()))
+ .rejects.toThrow('native-ota-contract-unavailable');
+ expect(h.bridge.cindyBeginSelfHostOtaRequest).not.toHaveBeenCalled();
+ expect(h.client.checkForUpdateAsync).not.toHaveBeenCalled();
+ });
+
+ it('restores after no update or an operation failure', async () => {
+ const h = harness();
+ await h.coordinator.run(options, async () => false);
+ await expect(h.coordinator.run(options, async () => { throw new Error('offline'); })).rejects.toThrow('offline');
+ await h.coordinator.run(options, async () => undefined);
+ expect(h.events).toEqual(['begin:beta', 'finish', 'begin:beta', 'finish', 'begin:beta', 'finish']);
+ });
+
+ it('keeps the queue locked until a timed-out native download really settles', async () => {
+ vi.useFakeTimers();
+ const h = harness();
+ let resolveDownload!: (value: { isNew: boolean; manifest: { id: string } }) => void;
+ h.client.fetchUpdateAsync.mockImplementationOnce(() => new Promise((resolve) => { resolveDownload = resolve; }));
+ const first = h.coordinator.run({ ...options, fetchTimeoutMs: 5 }, (client) => client.fetchUpdateAsync());
+ const rejected = expect(first).rejects.toThrow('ota-request-timeout');
+ await vi.advanceTimersByTimeAsync(5);
+ await rejected;
+ const second = h.coordinator.run({ ...options, channel: 'canary' }, async () => true);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(h.events).toEqual(['begin:beta']);
+ resolveDownload({ isNew: true, manifest: { id: 'u2' } });
+ expect(await second).toBe(true);
+ expect(h.events).toEqual(['begin:beta', 'finish', 'begin:canary', 'finish']);
+ });
+
+ it('does not reload the currently running update even when native reports it as new', async () => {
+ const h = harness();
+ h.client.checkForUpdateAsync.mockResolvedValue({ isAvailable: true, manifest: { id: 'U1' } });
+ h.client.fetchUpdateAsync.mockResolvedValue({ isNew: true, manifest: { id: 'U1' } });
+ await h.coordinator.run(options, async (client) => {
+ expect((await client.checkForUpdateAsync()).isAvailable).toBe(false);
+ expect((await client.fetchUpdateAsync()).isNew).toBe(false);
+ });
+ expect(h.client.reloadAsync).not.toHaveBeenCalled();
+ });
+
+ it('does not hide native restoration failures on a normally completed request', async () => {
+ const h = harness();
+ vi.mocked(h.bridge.cindyFinishSelfHostOtaRequest).mockImplementation(() => { throw new Error('disk-full'); });
+ await expect(h.coordinator.run(options, async () => true)).rejects.toThrow('disk-full');
+ });
+});
diff --git a/apps/mobile/src/update/nativeOtaRequestCoordinator.ts b/apps/mobile/src/update/nativeOtaRequestCoordinator.ts
new file mode 100644
index 0000000000..b0df268ea1
--- /dev/null
+++ b/apps/mobile/src/update/nativeOtaRequestCoordinator.ts
@@ -0,0 +1,104 @@
+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';
+import type { OtaRequestClient, OtaRequestTimeouts } from './otaRequestCoordinator';
+
+export interface NativeOtaBridge {
+ cindySelfHostOtaCapabilities: () => {
+ version: number;
+ runtimeVersion: string;
+ updateUrl: string;
+ available: boolean;
+ };
+ cindyBeginSelfHostOtaRequest: (channel: UpdateChannel) => string;
+ cindyFinishSelfHostOtaRequest: (token: string) => void;
+}
+
+interface RunOptions extends OtaRequestTimeouts {
+ channel: UpdateChannel;
+ currentUpdateId: string | null;
+ runtimeVersion: string | null;
+}
+
+function withTimeout<T>(promise: Promise<T>, milliseconds: number): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('ota-request-timeout(' + milliseconds + 'ms)')), milliseconds);
+ promise.then(
+ (value) => { clearTimeout(timer); resolve(value); },
+ (error: unknown) => { clearTimeout(timer); reject(error); },
+ );
+ });
+}
+
+/**
+ * The JS queue owns scheduling only. The native write-ahead journal owns header
+ * restoration, downloaded candidates, successful launches and cross-process
+ * recovery. A timeout does not cancel an Expo request or release this queue.
+ */
+export function createNativeOtaRequestCoordinator(bridge: NativeOtaBridge, client: OtaRequestClient) {
+ let queue: Promise<void> = Promise.resolve();
+
+ return {
+ run<T>(options: RunOptions, operation: (client: OtaRequestClient) => Promise<T>): Promise<T> {
+ const transaction = queue.then(() => {
+ const capability = bridge.cindySelfHostOtaCapabilities();
+ if (capability.version !== 1 || !capability.available ||
+ !options.runtimeVersion || capability.runtimeVersion !== options.runtimeVersion ||
+ !capability.updateUrl.startsWith('https://')) {
+ // Do not fall back to the legacy full override API on an incompatible
+ // or unavailable native adapter: anti-bricking intentionally forbids it.
+ throw new Error('native-ota-contract-unavailable');
+ }
+ const token = bridge.cindyBeginSelfHostOtaRequest(options.channel);
+ const requests: Promise<unknown>[] = [];
+ let finished = false;
+ const finish = () => {
+ if (finished) return;
+ bridge.cindyFinishSelfHostOtaRequest(token);
+ finished = true;
+ };
+ const track = <R>(promise: Promise<R>, budget: number) => {
+ requests.push(promise);
+ return withTimeout(promise, budget);
+ };
+ const currentId = options.currentUpdateId?.toLowerCase();
+ const coordinated: OtaRequestClient = {
+ checkForUpdateAsync: async () => {
+ const result = await track(client.checkForUpdateAsync(), options.checkTimeoutMs ?? 10_000);
+ if (currentId && result.manifest?.id?.toLowerCase() === currentId) {
+ return { ...result, isAvailable: false, manifest: undefined };
+ }
+ return result;
+ },
+ fetchUpdateAsync: async () => {
+ const result = await track(client.fetchUpdateAsync(), options.fetchTimeoutMs ?? 60_000);
+ if (currentId && result.manifest?.id?.toLowerCase() === currentId) {
+ return { ...result, isNew: false, manifest: undefined };
+ }
+ return result;
+ },
+ reloadAsync: async () => {
+ await Promise.allSettled(requests);
+ // A React reload destroys this queue too. Close the request before
+ // reloading; the native candidate receipt remains until CONTENT_APPEARED.
+ finish();
+ await client.reloadAsync();
+ },
+ };
+ const result = Promise.resolve().then(() => operation(coordinated));
+ const drained = result.then(() => undefined, () => undefined).then(async () => {
+ await Promise.allSettled(requests);
+ finish();
+ });
+ return { result, drained };
+ });
+ // An ordinary completed request reports restoration errors to its caller.
+ // A timed-out request can fail open while native completion still drains.
+ const result = transaction.then(async ({ result, drained }) => {
+ const value = await result;
+ await drained;
+ return value;
+ });
+ queue = transaction.then(({ drained }) => drained).then(() => undefined, () => undefined);
+ return result;
+ },
+ };
+}
diff --git a/apps/mobile/src/update/nativeOtaRouting.test.ts b/apps/mobile/src/update/nativeOtaRouting.test.ts
new file mode 100644
index 0000000000..c0cf759b6c
--- /dev/null
+++ b/apps/mobile/src/update/nativeOtaRouting.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { NativeOtaBridge } from './nativeOtaRequestCoordinator';
+
+const fixture = vi.hoisted(() => ({
+ module: null as Partial<NativeOtaBridge> | null,
+ endpoint: '',
+ check: vi.fn(), fetch: vi.fn(), reload: vi.fn(), legacyOverride: vi.fn(),
+ read: vi.fn(), write: vi.fn(),
+}));
+vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => fixture.module }));
+vi.mock('expo-updates', () => ({
+ updateId: 'u1', runtimeVersion: 'r1', isEmergencyLaunch: false,
+ checkForUpdateAsync: fixture.check, fetchUpdateAsync: fixture.fetch,
+ reloadAsync: fixture.reload, setUpdateURLAndRequestHeadersOverride: fixture.legacyOverride,
+}));
+vi.mock('@/config/env', () => ({ get OTA_SERVER_BASE_URL() { return fixture.endpoint; } }));
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {
+ getItem: fixture.read, setItem: fixture.write,
+} }));
+
+import { getNativeOtaBridge } from './nativeOtaBridge';
+import { runSelfHostedOtaRequest } from './otaRequestCoordinator';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ fixture.endpoint = '';
+ fixture.module = {
+ cindySelfHostOtaCapabilities: () => ({ version: 1, runtimeVersion: 'r1', available: true,
+ updateUrl: 'https://native.example.invalid/manifest' }),
+ cindyBeginSelfHostOtaRequest: vi.fn(() => 'request'),
+ cindyFinishSelfHostOtaRequest: vi.fn(),
+ };
+ fixture.check.mockResolvedValue({ isAvailable: false });
+});
+
+describe('installed binary OTA capability routing', () => {
+ it('uses native identity without a runtime endpoint or legacy JS journal', async () => {
+ await runSelfHostedOtaRequest('canary', (client) => client.checkForUpdateAsync());
+ expect(fixture.module?.cindyBeginSelfHostOtaRequest).toHaveBeenCalledWith('canary');
+ expect(fixture.module?.cindyFinishSelfHostOtaRequest).toHaveBeenCalledWith('request');
+ expect(fixture.check).toHaveBeenCalledOnce();
+ expect(fixture.legacyOverride).not.toHaveBeenCalled();
+ expect(fixture.read).not.toHaveBeenCalled();
+ expect(fixture.write).not.toHaveBeenCalled();
+ });
+
+ it('never substitutes the mutable runtime endpoint for the native endpoint', async () => {
+ fixture.endpoint = 'https://other.example.invalid';
+ await runSelfHostedOtaRequest('beta', (client) => client.checkForUpdateAsync());
+ expect(fixture.legacyOverride).not.toHaveBeenCalled();
+ expect(fixture.module?.cindyBeginSelfHostOtaRequest).toHaveBeenCalledWith('beta');
+ });
+
+ it('does not silently downgrade an incomplete native installation to full URL override', async () => {
+ delete fixture.module!.cindyFinishSelfHostOtaRequest;
+ await expect(runSelfHostedOtaRequest('release', (client) => client.checkForUpdateAsync()))
+ .rejects.toThrow('incomplete-native-ota-contract');
+ expect(fixture.check).not.toHaveBeenCalled();
+ expect(fixture.legacyOverride).not.toHaveBeenCalled();
+ });
+
+ it('leaves an old binary on the legacy path, including its endpoint prerequisite', async () => {
+ fixture.module = null;
+ expect(getNativeOtaBridge()).toBeNull();
+ await expect(runSelfHostedOtaRequest('release', (client) => client.checkForUpdateAsync()))
+ .rejects.toThrow('endpoint manifest missing mobileUpdateBaseUrl');
+ expect(fixture.check).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/update/otaRequestCoordinator.test.ts b/apps/mobile/src/update/otaRequestCoordinator.test.ts
index 750e38f6f9..3c783e69e8 100644
--- a/apps/mobile/src/update/otaRequestCoordinator.test.ts
+++ b/apps/mobile/src/update/otaRequestCoordinator.test.ts
@@ -29,6 +29,7 @@ vi.mock('expo-updates', () => ({
...nativeUpdates,
}));
vi.mock('@/config/env', () => ({ OTA_SERVER_BASE_URL: 'https://updates.example.test' }));
+vi.mock('./nativeOtaBridge', () => ({ getNativeOtaBridge: () => null }));
import type { UpdateChannel } from '@cindy/maker-shared/update-channel';
import {
diff --git a/apps/mobile/src/update/otaRequestCoordinator.ts b/apps/mobile/src/update/otaRequestCoordinator.ts
index 7278a0833a..c8fc36191a 100644
--- a/apps/mobile/src/update/otaRequestCoordinator.ts
+++ b/apps/mobile/src/update/otaRequestCoordinator.ts
@@ -5,6 +5,8 @@ import type { UpdateChannel } from '@cindy/maker-shared/update-channel';
import { OTA_SERVER_BASE_URL } from '@/config/env';
import { updateChannelRequestHeaders } from './canaryChannelStore';
+import { getNativeOtaBridge } from './nativeOtaBridge';
+import { createNativeOtaRequestCoordinator, type NativeOtaBridge } from './nativeOtaRequestCoordinator';
/**
* expo-updates 要求 EAS-Client-ID 是合法 UUID;自建 OTA 全设备共用这个非设备标识值。
@@ -356,6 +358,8 @@ const nativeCoordinator = createOtaRequestCoordinator({
},
});
+const nativeV1Coordinators = new WeakMap<NativeOtaBridge, ReturnType<typeof createNativeOtaRequestCoordinator>>();
+
/** 自建 OTA 的唯一网络入口;启动、回前台、手动检查必须全部走这里。 */
export function runSelfHostedOtaRequest<T>(
channel: UpdateChannel,
@@ -365,6 +369,31 @@ export function runSelfHostedOtaRequest<T>(
fetchTimeoutMs = DEFAULT_FETCH_TIMEOUT_MS,
}: OtaRequestTimeouts = {},
): Promise<T> {
+ try {
+ const bridge = getNativeOtaBridge();
+ if (bridge) {
+ let coordinator = nativeV1Coordinators.get(bridge);
+ if (!coordinator) {
+ coordinator = createNativeOtaRequestCoordinator(bridge, {
+ checkForUpdateAsync: () => Updates.checkForUpdateAsync(),
+ fetchUpdateAsync: () => Updates.fetchUpdateAsync(),
+ reloadAsync: () => Updates.reloadAsync(),
+ });
+ nativeV1Coordinators.set(bridge, coordinator);
+ }
+ return coordinator.run({
+ channel,
+ currentUpdateId: Updates.updateId,
+ runtimeVersion: Updates.runtimeVersion,
+ checkTimeoutMs,
+ fetchTimeoutMs,
+ }, operation);
+ }
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ // Old binaries retain the already-shipped bridge behavior and URL source.
+ // Native v1 never reads or persists this mutable endpoint as its OTA identity.
if (!OTA_SERVER_BASE_URL) {
return Promise.reject(new Error('endpoint manifest missing mobileUpdateBaseUrl'));
}