From 6c4fed9d52bb5efa07341858898e8b130373e5d7 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 14:08:41 +0800 Subject: [PATCH 1/7] feat(device-utils): add synchronous first-launch tracking API --- .../react-native-device-utils/README.md | 49 +++ .../DeviceUtilsFirstLaunch.kt | 101 +++++ .../FirstLaunchHistory.kt | 228 ++++++++++++ .../ReactNativeDeviceUtils.kt | 9 + .../react-native-device-utils/babel.config.js | 10 - .../react-native-device-utils/docs/SPEC.md | 52 +++ .../ios/DeviceUtilsFirstLaunch.swift | 297 +++++++++++++++ .../ios/ReactNativeDeviceUtils.swift | 12 + .../react-native-device-utils/package.json | 13 + .../src/ReactNativeDeviceUtils.nitro.ts | 6 + .../src/__tests__/firstLaunch.test.ts | 186 ++++++++++ .../src/firstLaunch.native.ts | 40 ++ .../src/firstLaunch.web.ts | 350 ++++++++++++++++++ .../tests/InMemoryStoreTest.kt | 47 +++ .../tests/in-memory-store.cjs | 2 + .../tests/main.swift | 66 ++++ .../react-native-device-utils/tsconfig.json | 2 +- 17 files changed, 1459 insertions(+), 11 deletions(-) create mode 100644 native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt create mode 100644 native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt create mode 100644 native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift create mode 100644 native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts create mode 100644 native-modules/react-native-device-utils/src/firstLaunch.native.ts create mode 100644 native-modules/react-native-device-utils/src/firstLaunch.web.ts diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index cb8ef84f5..88b332cb1 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -63,6 +63,11 @@ ReactNativeDeviceUtils.initEventListeners(); const { launchType, deepLink } = await ReactNativeDeviceUtils.getLaunchOptions(); const startupTime = await ReactNativeDeviceUtils.getStartupTime(); +const isFirstLaunch = ReactNativeDeviceUtils.isFirstLaunch(); +const isFirstAppVersionLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); +const isFirstBundleLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle( + process.env.BUNDLE_VERSION, +); // Claim a startup stage exactly once across runtimes. const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent( @@ -74,6 +79,47 @@ const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent( Consumers own key namespaces and decide what to do with each result. Store values are native copies, not retained JS objects. +### First launch in shared code + +The following entry point works in React Native, Web, Electron renderers, +and extension pages. Call `initFirstLaunch` once at app startup, then read +the cached booleans synchronously anywhere: + +```ts +import { + initFirstLaunch, + isFirstLaunch, + isFirstLaunchForCurrentAppVersion, + isFirstLaunchForCurrentBundle, +} from '@onekeyfe/react-native-device-utils/first-launch'; + +// Call once at app startup. On Web/Desktop/Extension, pass host-sampled +// `isLegacyInstall` / `legacyAppVersion` if upgrading from versions before this API. +initFirstLaunch({ + appVersion, + bundleVersion, + isLegacyInstall, +}); + +// Pure in-memory reads during the current launch. +const firstLaunch = isFirstLaunch(); +const firstAppVersionLaunch = isFirstLaunchForCurrentAppVersion(); +const firstBundleLaunch = isFirstLaunchForCurrentBundle(); +``` + +On iOS and Android, initialize the pure native singleton early in +`AppDelegate.didFinishLaunchingWithOptions` (`OneKeyDeviceUtilsFirstLaunch` via +`initializeWithOptions:` / `hasPersistedState`) or `Application.onCreate()` +(`DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... })`) so +host-specific legacy upgrade detection stays in the app and runs before React Native starts. + +Persisted state is a fixed 3-field record (`hasLaunched`, `highestAppVersion`, +`highestBundleVersion`), so storage never grows and requires no cleanup. +Rolling back to a version lower than the recorded highest version returns `false`. +Outside React Native, the record is stored in `localStorage` under +`onekey:device-utils:first-launch`. Call from an extension-owned UI page; an MV3 +service worker returns `false`. + ## API | Method | Result | Platforms | Description | @@ -81,6 +127,9 @@ values are native copies, not retained JS objects. | `initEventListeners()` | `void` | iOS, Android | Registers native listeners; call once at startup. | | `getLaunchOptions()` / `clearLaunchOptions()` | `Promise` / `Promise` | iOS, Android | Read or consume the app's launch type and optional deep link. | | `getStartupTime()` | `Promise` | iOS, Android | Native startup timestamp. | +| `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. | +| `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. | +| `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. | | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise` / `Promise` / `Promise` | iOS, Android | Push-token plumbing; host setup still owns registration. | | `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. | | `getAndClearColdStartLocalNotification()` | `Promise` | iOS, Android | Returns local-notification JSON once; Android returns `""`. | diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt new file mode 100644 index 000000000..0dd8ec9b8 --- /dev/null +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt @@ -0,0 +1,101 @@ +package com.margelo.nitro.reactnativedeviceutils + +import android.content.Context +import android.content.pm.PackageManager +import java.io.File + +/** + * Pure native process-wide singleton for first-launch tracking. + * Has no Nitro/JSI dependencies, so host apps can initialize it early in + * `Application.onCreate()` before React Native starts. + */ +object DeviceUtilsFirstLaunch { + private val lock = Any() + + @Volatile + private var history: FirstLaunchHistory? = null + + /** + * Returns true if the persisted first-launch state file already exists on disk. + */ + @JvmStatic + fun hasPersistedState(context: Context): Boolean { + val filesDir = context.applicationContext?.filesDir ?: context.filesDir ?: return false + return File(filesDir, FirstLaunchHistory.FILE_NAME).exists() + } + + /** + * Initializes the process-wide first-launch state. Subsequent calls are no-ops. + */ + @JvmStatic + @JvmOverloads + fun initialize( + context: Context, + isLegacyInstall: Boolean = false, + legacyAppVersion: String? = null, + ) { + initialize( + context = context, + isLegacyInstall = { isLegacyInstall }, + legacyAppVersion = { legacyAppVersion }, + ) + } + + /** + * Kotlin-friendly initializer whose legacy-detection lambdas are only evaluated + * when no persisted state file exists yet. + */ + fun initialize( + context: Context, + isLegacyInstall: () -> Boolean, + legacyAppVersion: () -> String? = { null }, + ) { + if (history != null) return + synchronized(lock) { + if (history != null) return + val appContext = context.applicationContext ?: context + val filesDirectory = appContext.filesDir ?: return + val versionName = try { + @Suppress("DEPRECATION") + appContext.packageManager.getPackageInfo(appContext.packageName, 0).versionName + } catch (_: PackageManager.NameNotFoundException) { + null + } catch (_: SecurityException) { + null + } + val persistedExists = File(filesDirectory, FirstLaunchHistory.FILE_NAME).exists() + val hasPreviousLaunch = if (persistedExists) false else runCatching(isLegacyInstall).getOrDefault(false) + val previousVersion = if (persistedExists) null else runCatching(legacyAppVersion).getOrNull() + history = FirstLaunchHistory( + directory = filesDirectory, + appVersion = versionName, + previousAppVersion = previousVersion, + hasPreviousLaunch = hasPreviousLaunch, + ) + } + } + + internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean { + ensureInitialized(fallbackContext) + return history?.isFirstLaunch ?: false + } + + internal fun isFirstLaunchForCurrentAppVersion(fallbackContext: Context? = null): Boolean { + ensureInitialized(fallbackContext) + return history?.isFirstLaunchForCurrentAppVersion ?: false + } + + internal fun isFirstLaunchForBundle( + bundleVersion: String?, + fallbackContext: Context? = null, + ): Boolean { + ensureInitialized(fallbackContext) + return history?.isFirstLaunchForBundle(bundleVersion) ?: false + } + + private fun ensureInitialized(fallbackContext: Context?) { + if (history == null && fallbackContext != null) { + initialize(fallbackContext) + } + } +} diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt new file mode 100644 index 000000000..52fad2447 --- /dev/null +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -0,0 +1,228 @@ +package com.margelo.nitro.reactnativedeviceutils + +import java.io.File +import java.io.IOException + +internal class FirstLaunchHistory( + directory: File, + appVersion: String?, + previousAppVersion: String?, + hasPreviousLaunch: Boolean, +) { + private data class PersistedState( + val hasLaunched: Boolean, + val highestAppVersion: String?, + val highestBundleVersion: String?, + ) + + val isFirstLaunch: Boolean + val isFirstLaunchForCurrentAppVersion: Boolean + private val directory: File = directory + private val stateFile = File(directory, FILE_NAME) + private var persisted: PersistedState + private val storageAvailable: Boolean + private val bundleResults = mutableMapOf() + private var lastBundleVersion: String? = null + + init { + val validPrevious = validatedVersion(previousAppVersion) + val validCurrent = validatedVersion(appVersion) + val fileExists = stateFile.exists() + val loaded = readState(stateFile) + if (fileExists && loaded == null) { + storageAvailable = false + persisted = PersistedState( + hasLaunched = true, + highestAppVersion = validPrevious, + highestBundleVersion = null, + ) + isFirstLaunch = false + isFirstLaunchForCurrentAppVersion = false + } else { + var state = loaded ?: PersistedState( + hasLaunched = false, + highestAppVersion = validPrevious, + highestBundleVersion = null, + ) + var needsWrite = loaded == null + + val computedFirstLaunch = !state.hasLaunched && !hasPreviousLaunch + if (!state.hasLaunched) { + state = state.copy(hasLaunched = true) + needsWrite = true + } + + val computedFirstAppVersion = if (validCurrent != null) { + val baseline = state.highestAppVersion + val isHigher = baseline == null || compareVersions(validCurrent, baseline) > 0 + if (isHigher) { + state = state.copy(highestAppVersion = validCurrent) + needsWrite = true + } + isHigher + } else { + false + } + + if (needsWrite) { + if (writeState(state)) { + storageAvailable = true + persisted = state + isFirstLaunch = computedFirstLaunch + isFirstLaunchForCurrentAppVersion = computedFirstAppVersion + } else { + storageAvailable = false + persisted = state + isFirstLaunch = false + isFirstLaunchForCurrentAppVersion = false + } + } else { + storageAvailable = true + persisted = state + isFirstLaunch = computedFirstLaunch + isFirstLaunchForCurrentAppVersion = computedFirstAppVersion + } + } + } + + @Synchronized + fun isFirstLaunchForBundle(bundleVersion: String?): Boolean { + if (bundleVersion == null) { + return lastBundleVersion?.let { bundleResults[it] } ?: false + } + val validBundle = validatedVersion(bundleVersion) ?: return false + bundleResults[validBundle]?.let { + lastBundleVersion = validBundle + return it + } + if (!storageAvailable) { + bundleResults[validBundle] = false + lastBundleVersion = validBundle + return false + } + val baseline = persisted.highestBundleVersion + val isHigher = baseline == null || compareVersions(validBundle, baseline) > 0 + if (isHigher) { + val next = persisted.copy(highestBundleVersion = validBundle) + if (!writeState(next)) { + bundleResults[validBundle] = false + lastBundleVersion = validBundle + return false + } + persisted = next + } + bundleResults[validBundle] = isHigher + lastBundleVersion = validBundle + return isHigher + } + + private fun readState(file: File): PersistedState? = try { + if (!file.isFile) { + null + } else { + val text = file.readText(Charsets.UTF_8) + val hasLaunched = Regex(""""hasLaunched"\s*:\s*(true|false)""") + .find(text)?.groupValues?.get(1) == "true" + val highestApp = Regex(""""highestAppVersion"\s*:\s*"([^"]*)"""") + .find(text)?.groupValues?.get(1)?.let(::validatedVersion) + val highestBundle = Regex(""""highestBundleVersion"\s*:\s*"([^"]*)"""") + .find(text)?.groupValues?.get(1)?.let(::validatedVersion) + PersistedState( + hasLaunched = hasLaunched, + highestAppVersion = highestApp, + highestBundleVersion = highestBundle, + ) + } + } catch (_: IOException) { + null + } catch (_: SecurityException) { + null + } + + private fun writeState(state: PersistedState): Boolean = try { + if (!directory.exists() && !directory.mkdirs() && !directory.isDirectory) { + false + } else if (!directory.isDirectory) { + false + } else { + val appJson = state.highestAppVersion?.let { "\"$it\"" } ?: "null" + val bundleJson = state.highestBundleVersion?.let { "\"$it\"" } ?: "null" + val json = + """{"hasLaunched":${state.hasLaunched},"highestAppVersion":$appJson,"highestBundleVersion":$bundleJson}""" + val temp = File(directory, "${stateFile.name}.tmp") + temp.writeText(json, Charsets.UTF_8) + if (!temp.renameTo(stateFile)) { + stateFile.writeText(json, Charsets.UTF_8) + temp.delete() + } + true + } + } catch (_: IOException) { + false + } catch (_: SecurityException) { + false + } + + companion object { + internal const val FILE_NAME = "onekey-device-utils-first-launch.json" + + internal fun validatedVersion(version: String?): String? { + if (version == null || version.length !in 1..120) return null + if (!version.all { it in '0'..'9' || it in 'A'..'Z' || it in 'a'..'z' || it in "._-+" }) return null + return version + } + + internal fun compareVersions(a: String, b: String): Int { + fun stripBuild(v: String): String { + val idx = v.indexOf('+') + return if (idx >= 0) v.substring(0, idx) else v + } + fun splitPre(v: String): Pair { + val idx = v.indexOf('-') + return if (idx >= 0) v.substring(0, idx) to v.substring(idx + 1) else v to null + } + fun isDigits(s: String): Boolean = s.isNotEmpty() && s.all { it in '0'..'9' } + fun compareUnsigned(lhs: String, rhs: String): Int { + val normA = lhs.trimStart('0').ifEmpty { "0" } + val normB = rhs.trimStart('0').ifEmpty { "0" } + if (normA.length != normB.length) return if (normA.length < normB.length) -1 else 1 + return normA.compareTo(normB) + } + fun compareIdent(lhs: String, rhs: String): Int { + val aNum = isDigits(lhs) + val bNum = isDigits(rhs) + if (aNum && bNum) return compareUnsigned(lhs, rhs) + if (aNum != bNum) return if (aNum) -1 else 1 + return lhs.compareTo(rhs) + } + + val (mainA, preA) = splitPre(stripBuild(a)) + val (mainB, preB) = splitPre(stripBuild(b)) + val segA = mainA.split('.') + val segB = mainB.split('.') + val maxLen = maxOf(segA.size, segB.size) + + for (i in 0 until maxLen) { + val partA = if (i < segA.size) segA[i] else "0" + val partB = if (i < segB.size) segB[i] else "0" + val cmp = compareIdent(partA, partB) + if (cmp != 0) return cmp + } + + if (preA == null && preB == null) return 0 + if (preA == null) return 1 + if (preB == null) return -1 + + val preSegA = preA.split('.') + val preSegB = preB.split('.') + val maxPre = maxOf(preSegA.size, preSegB.size) + for (i in 0 until maxPre) { + if (i >= preSegA.size) return -1 + if (i >= preSegB.size) return 1 + val cmp = compareIdent(preSegA[i], preSegB[i]) + if (cmp != 0) return cmp + } + return 0 + } + } +} diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 54d8c887b..5e98644f1 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -46,6 +46,15 @@ private data class NavigationBarAppearance( @DoNotStrip class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEventListener { + override fun isFirstLaunch(): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunch(NitroModules.applicationContext) + + override fun isFirstLaunchForCurrentAppVersion(): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunchForCurrentAppVersion(NitroModules.applicationContext) + + override fun isFirstLaunchForCurrentBundle(bundleVersion: String?): Boolean = + DeviceUtilsFirstLaunch.isFirstLaunchForBundle(bundleVersion, NitroModules.applicationContext) + override fun getInMemoryValue(key: String): InMemoryValue? = InMemoryStore.get(key) override fun setInMemoryValue(key: String, value: InMemoryValue) = InMemoryStore.set(key, value) diff --git a/native-modules/react-native-device-utils/babel.config.js b/native-modules/react-native-device-utils/babel.config.js index 7d6b2cd2e..98655448c 100644 --- a/native-modules/react-native-device-utils/babel.config.js +++ b/native-modules/react-native-device-utils/babel.config.js @@ -1,13 +1,3 @@ module.exports = { presets: ['@react-native/babel-preset'], - plugins: [ - [ - 'module-resolver', - { - alias: { - 'react-native-device-utils': './src/index', - }, - }, - ], - ], }; diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 0701b0809..f31d20205 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -1,3 +1,55 @@ +# DeviceUtils: first launch + +## Status and scope + +The iOS and Android Nitro first-launch getters return synchronous booleans. Results are +shared by the main and background JavaScript runtimes and stay fixed for each +identity across JS reloads and foreground transitions within the same process. +Background process starts that run the normal native app bootstrap also count. + +| Method | First launch identity | +| --- | --- | +| `isFirstLaunch()` | The local app installation. | +| `isFirstLaunchForCurrentAppVersion()` | The native app's release version (`CFBundleShortVersionString` on iOS, `versionName` on Android). Build number changes alone keep the same identity. | +| `isFirstLaunchForCurrentBundle(bundleVersion?: string)` | The unique version embedded in the executing JS bundle. Call at JS startup with that version for built-in and OTA bundles. | + +## Lifecycle, persistence, and platform behavior + +Persisted state is stored as a fixed 3-field JSON object: + +```json +{ + "hasLaunched": true, + "highestAppVersion": "6.5.0", + "highestBundleVersion": "1000" +} +``` + +Because only these three fields are persisted, storage size is constant and no cleanup or history pruning API is needed. + +On each launch, the startup path performs a single **read persisted state → compute and freeze current-launch booleans in memory → advance persisted fields if needed** cycle. All getters during that launch return the frozen in-memory booleans and never re-evaluate against the updated disk values. + +| Platform | Initialization | Storage | Legacy-install evidence | +| --- | --- | --- | --- | +| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in Application Support | Owned by the host app. Use `hasPersistedState()` to skip legacy checks once persisted state exists. | +| Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in `context.filesDir` | Owned by the host app (lambdas are only invoked when no persisted file exists yet). | +| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` at UI startup. | `localStorage` key `onekey:device-utils:first-launch` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | + +Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted field. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. + +Missing startup initialization, unavailable or corrupted storage, invalid identifiers (must be 1–120 ASCII `[0-9A-Za-z._+-]`), and write failures fail safe and return `false`. There are no network calls, JS callbacks, async waits, or wallet reads. Native app-install and app-version state are recorded during native startup even if JavaScript never calls a getter. Call `initFirstLaunch({ appVersion, bundleVersion })` at app JS startup so bundle versions on native and all three dimensions on Web/Desktop/Extension are recorded unconditionally. + +## Web, desktop renderer, and extension pages + +The `@onekeyfe/react-native-device-utils/first-launch` entry point exposes: + +- `initFirstLaunch(options?: { appVersion?: string; bundleVersion?: string }): void` +- `isFirstLaunch(): boolean` +- `isFirstLaunchForCurrentAppVersion(appVersion?: string): boolean` +- `isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean` + +React Native delegates to `ReactNativeDeviceUtils`. Web documents, Electron renderers, and extension-owned pages share `src/firstLaunch.web.ts` backed by `window.localStorage`. After `initFirstLaunch(...)` runs at startup, getters can be called with zero arguments to read the cached launch results. Server runtimes and MV3 service workers have no `window.localStorage` and return `false`. + # DeviceUtils: InMemoryStore contract ## Status and scope diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift new file mode 100644 index 000000000..ac97e0f86 --- /dev/null +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -0,0 +1,297 @@ +import Foundation + +@objc(OneKeyDeviceUtilsFirstLaunch) +public final class DeviceUtilsFirstLaunch: NSObject { + private static let lock = NSLock() + private static var history: FirstLaunchHistory? + + /// Returns true if the persisted first-launch state file already exists on disk. + /// Safe to call via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` before + /// running host-specific legacy upgrade checks. + @objc public static func hasPersistedState() -> Bool { + guard let directory = defaultDirectory() else { return false } + let fileURL = directory.appendingPathComponent(FirstLaunchHistory.fileName) + return FileManager.default.fileExists(atPath: fileURL.path) + } + + /// Initializes the process-wide first-launch state from the host app (e.g. AppDelegate). + /// Accepts an Objective-C `NSDictionary` so Swift hosts can invoke it dynamically via + /// `NSClassFromString` + `perform(_:with:)` without importing Nitro C++ headers. + /// Supported keys: + /// - `"isLegacyInstall"`: `NSNumber` / `Bool` (default `false`) + /// - `"legacyAppVersion"`: `NSString` / `String` (optional) + @objc(initializeWithOptions:) + public static func initialize(options: NSDictionary?) { + let isLegacyInstall = (options?["isLegacyInstall"] as? NSNumber)?.boolValue ?? false + let legacyAppVersion = options?["legacyAppVersion"] as? String + initialize(isLegacyInstall: isLegacyInstall, legacyAppVersion: legacyAppVersion) + } + + /// Swift-friendly initializer for hosts that can import this module directly. + public static func initialize( + isLegacyInstall: Bool = false, + legacyAppVersion: String? = nil + ) { + lock.lock() + defer { lock.unlock() } + guard history == nil else { return } + guard let directory = defaultDirectory() else { return } + history = FirstLaunchHistory( + directory: directory, + appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, + previousAppVersion: legacyAppVersion, + hasPreviousLaunch: isLegacyInstall + ) + } + + static var value: Bool { + withHistory(default: false) { $0.isFirstLaunch } + } + + static var forCurrentAppVersion: Bool { + withHistory(default: false) { $0.isFirstLaunchForCurrentAppVersion } + } + + static func forBundle(_ bundleVersion: String?) -> Bool { + withHistory(default: false) { $0.isFirstLaunchForBundle(bundleVersion) } + } + + private static func defaultDirectory() -> URL? { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first + } + + private static func withHistory(default fallback: Result, _ read: (FirstLaunchHistory) -> Result) -> Result { + lock.lock() + defer { lock.unlock() } + if let existing = history { + return read(existing) + } + guard let directory = defaultDirectory() else { + return fallback + } + let created = FirstLaunchHistory( + directory: directory, + appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, + previousAppVersion: nil, + hasPreviousLaunch: false + ) + history = created + return read(created) + } +} + +final class FirstLaunchHistory { + static let fileName = "onekey-device-utils-first-launch.json" + + private struct PersistedState: Codable { + var hasLaunched: Bool + var highestAppVersion: String? + var highestBundleVersion: String? + } + + let isFirstLaunch: Bool + let isFirstLaunchForCurrentAppVersion: Bool + private let fileURL: URL + private var persisted: PersistedState + private var storageAvailable: Bool + private var bundleResults: [String: Bool] = [:] + private var lastBundleVersion: String? + + init(directory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { + fileURL = directory.appendingPathComponent(Self.fileName) + let validPrevious = Self.validatedVersion(previousAppVersion) + let validCurrent = Self.validatedVersion(appVersion) + + let fileExists = FileManager.default.fileExists(atPath: fileURL.path) + let loaded = Self.readState(from: fileURL) + if fileExists && loaded == nil { + storageAvailable = false + persisted = PersistedState(hasLaunched: true, highestAppVersion: validPrevious, highestBundleVersion: nil) + isFirstLaunch = false + isFirstLaunchForCurrentAppVersion = false + return + } + var state = loaded ?? PersistedState( + hasLaunched: false, + highestAppVersion: validPrevious, + highestBundleVersion: nil + ) + var needsWrite = loaded == nil + + let computedFirstLaunch = !state.hasLaunched && !hasPreviousLaunch + if !state.hasLaunched { + state.hasLaunched = true + needsWrite = true + } + + let computedFirstAppVersion: Bool + if let validCurrent { + let baseline = state.highestAppVersion + let isHigher = baseline == nil || Self.compareVersions(validCurrent, baseline!) > 0 + computedFirstAppVersion = isHigher + if isHigher { + state.highestAppVersion = validCurrent + needsWrite = true + } + } else { + computedFirstAppVersion = false + } + + if needsWrite { + if Self.writeState(state, to: fileURL, directory: directory) { + storageAvailable = true + persisted = state + isFirstLaunch = computedFirstLaunch + isFirstLaunchForCurrentAppVersion = computedFirstAppVersion + } else { + storageAvailable = false + persisted = state + isFirstLaunch = false + isFirstLaunchForCurrentAppVersion = false + } + } else { + storageAvailable = true + persisted = state + isFirstLaunch = computedFirstLaunch + isFirstLaunchForCurrentAppVersion = computedFirstAppVersion + } + } + + func isFirstLaunchForBundle(_ bundleVersion: String?) -> Bool { + guard let bundleVersion else { + return lastBundleVersion.flatMap { bundleResults[$0] } ?? false + } + guard let validBundle = Self.validatedVersion(bundleVersion) else { + return false + } + if let cached = bundleResults[validBundle] { + lastBundleVersion = validBundle + return cached + } + guard storageAvailable else { + bundleResults[validBundle] = false + lastBundleVersion = validBundle + return false + } + let baseline = persisted.highestBundleVersion + let isHigher = baseline == nil || Self.compareVersions(validBundle, baseline!) > 0 + if isHigher { + var next = persisted + next.highestBundleVersion = validBundle + guard Self.writeState(next, to: fileURL, directory: fileURL.deletingLastPathComponent()) else { + bundleResults[validBundle] = false + lastBundleVersion = validBundle + return false + } + persisted = next + } + bundleResults[validBundle] = isHigher + lastBundleVersion = validBundle + return isHigher + } + + static func compareVersions(_ a: String, _ b: String) -> Int { + func stripBuild(_ v: String) -> Substring { + if let plus = v.firstIndex(of: "+") { + return v[.. (Substring, Substring?) { + if let dash = v.firstIndex(of: "-") { + return (v[.. Bool { + !s.isEmpty && s.utf8.allSatisfy { $0 >= 48 && $0 <= 57 } + } + func compareUnsigned(_ lhs: Substring, _ rhs: Substring) -> Int { + let normA = lhs.drop { $0 == "0" } + let normB = rhs.drop { $0 == "0" } + if normA.count != normB.count { + return normA.count < normB.count ? -1 : 1 + } + if normA == normB { return 0 } + return normA < normB ? -1 : 1 + } + func compareIdent(_ lhs: Substring, _ rhs: Substring) -> Int { + let aNum = isDigits(lhs) + let bNum = isDigits(rhs) + if aNum && bNum { + return compareUnsigned(lhs, rhs) + } + if aNum != bNum { + return aNum ? -1 : 1 + } + if lhs == rhs { return 0 } + return lhs < rhs ? -1 : 1 + } + + let (mainA, preA) = splitPre(stripBuild(a)) + let (mainB, preB) = splitPre(stripBuild(b)) + let segA = mainA.split(separator: ".", omittingEmptySubsequences: false) + let segB = mainB.split(separator: ".", omittingEmptySubsequences: false) + let maxLen = max(segA.count, segB.count) + let zero: Substring = "0" + + for i in 0..= preSegA.count { return -1 } + if i >= preSegB.count { return 1 } + let cmp = compareIdent(preSegA[i], preSegB[i]) + if cmp != 0 { return cmp } + } + return 0 + } + } + + private static func validatedVersion(_ version: String?) -> String? { + guard let version, (1...120).contains(version.utf8.count), + version.utf8.allSatisfy({ + switch $0 { + case 43, 45, 46, 48...57, 65...90, 95, 97...122: return true + default: return false + } + }) else { return nil } + return version + } + + private static func readState(from url: URL) -> PersistedState? { + guard let data = try? Data(contentsOf: url), + var decoded = try? JSONDecoder().decode(PersistedState.self, from: data) else { + return nil + } + decoded.highestAppVersion = validatedVersion(decoded.highestAppVersion) + decoded.highestBundleVersion = validatedVersion(decoded.highestBundleVersion) + return decoded + } + + private static func writeState(_ state: PersistedState, to url: URL, directory: URL) -> Bool { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let data = try JSONEncoder().encode(state) + try data.write(to: url, options: .atomic) + return true + } catch { + return false + } + } +} diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 4b52535c8..243c3be9c 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -74,6 +74,18 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { private static let userInterfaceStyleKey = "1k_user_interface_style" + func isFirstLaunch() throws -> Bool { + DeviceUtilsFirstLaunch.value + } + + func isFirstLaunchForCurrentAppVersion() throws -> Bool { + DeviceUtilsFirstLaunch.forCurrentAppVersion + } + + func isFirstLaunchForCurrentBundle(bundleVersion: String?) throws -> Bool { + DeviceUtilsFirstLaunch.forBundle(bundleVersion) + } + override init() { super.init() restoreUserInterfaceStyle() diff --git a/native-modules/react-native-device-utils/package.json b/native-modules/react-native-device-utils/package.json index 92c1ec621..f5cc4b1e1 100644 --- a/native-modules/react-native-device-utils/package.json +++ b/native-modules/react-native-device-utils/package.json @@ -10,6 +10,19 @@ "types": "./lib/typescript/src/index.d.ts", "default": "./lib/module/index.js" }, + "./first-launch": { + "types": "./lib/typescript/src/firstLaunch.web.d.ts", + "browser": { + "source": "./src/firstLaunch.web.ts", + "default": "./lib/module/firstLaunch.web.js" + }, + "react-native": { + "source": "./src/firstLaunch.native.ts", + "default": "./lib/module/firstLaunch.native.js" + }, + "source": "./src/firstLaunch.web.ts", + "default": "./lib/module/firstLaunch.web.js" + }, "./package.json": "./package.json" }, "files": [ diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 95388dd83..619eefa60 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -129,6 +129,12 @@ export interface ReactNativeDeviceUtils saveDeviceToken(token: string): Promise; registerDeviceToken(): Promise; getStartupTime(): Promise; + /** Whether the current native process is the first launch of this local installation. */ + isFirstLaunch(): boolean; + /** First launch of a native release version higher than any previously launched version. */ + isFirstLaunchForCurrentAppVersion(): boolean; + /** First launch of a bundle version higher than any previously launched bundle. */ + isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean; // Process-owned primitive Map, shared by all runtimes and never persisted. getInMemoryValue(key: string): InMemoryValue | undefined; setInMemoryValue(key: string, value: InMemoryValue): void; diff --git a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts new file mode 100644 index 000000000..f95184abd --- /dev/null +++ b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts @@ -0,0 +1,186 @@ +const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); + +function openDocument( + localStorage?: Pick +) { + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: localStorage ? { localStorage } : undefined, + }); + return loadModule(); +} + +function loadModule() { + let result!: typeof import('../firstLaunch.web'); + jest.isolateModules(() => { + result = jest.requireActual( + '../firstLaunch.web' + ); + }); + return result; +} + +function createStorage(initialEntries?: Record) { + const values = new Map( + initialEntries ? Object.entries(initialEntries) : [] + ); + return { + get length() { + return values.size; + }, + getItem: jest.fn((key: string) => values.get(key) ?? null), + setItem: jest.fn((key: string, value: string) => { + values.set(key, value); + }), + removeItem: jest.fn((key: string) => { + values.delete(key); + }), + }; +} + +afterEach(() => { + if (originalWindow) { + Object.defineProperty(globalThis, 'window', originalWindow); + } else { + Reflect.deleteProperty(globalThis, 'window'); + } +}); + +it('records installation, highest app version, and highest bundle version via initFirstLaunch', () => { + const storage = createStorage(); + const startup = openDocument(storage); + + startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(startup.isFirstLaunch()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); + // Repeated calls during the same launch stay stable and read from memory. + expect(startup.isFirstLaunch()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); + + const reload = openDocument(storage); + reload.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(reload.isFirstLaunch()).toBe(false); + expect(reload.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(reload.isFirstLaunchForCurrentBundle()).toBe(false); + + // Higher bundle only + const ota = openDocument(storage); + ota.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1001' }); + expect(ota.isFirstLaunch()).toBe(false); + expect(ota.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); + expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); + + // Rollback to lower bundle returns false and preserves highestBundleVersion + const rollback = openDocument(storage); + rollback.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(rollback.isFirstLaunch()).toBe(false); + expect(rollback.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(rollback.isFirstLaunchForCurrentBundle()).toBe(false); + + // Upgrade app version (6.10.0 > 6.5.0 numerically) with same bundle + const upgrade = openDocument(storage); + upgrade.initFirstLaunch({ appVersion: '6.10.0', bundleVersion: '1001' }); + expect(upgrade.isFirstLaunch()).toBe(false); + expect(upgrade.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(upgrade.isFirstLaunchForCurrentBundle()).toBe(false); + + // Downgrade app version returns false + const downgrade = openDocument(storage); + downgrade.initFirstLaunch({ appVersion: '6.9.0', bundleVersion: '999' }); + expect(downgrade.isFirstLaunch()).toBe(false); + expect(downgrade.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(downgrade.isFirstLaunchForCurrentBundle()).toBe(false); +}); + +it('honors host-provided legacy upgrade flags without guessing from unrelated keys', () => { + // Unrelated third-party keys in localStorage should NOT trigger legacy detection on their own. + const thirdPartyStorage = createStorage({ 'third-party-sdk': '1' }); + const freshWithNoise = openDocument(thirdPartyStorage); + freshWithNoise.initFirstLaunch({ + appVersion: '6.5.0', + bundleVersion: '1000', + }); + expect(freshWithNoise.isFirstLaunch()).toBe(true); + + // Host explicitly signals legacy install + previous version. + const legacyStorage = createStorage(); + const upgradedSame = openDocument(legacyStorage); + upgradedSame.initFirstLaunch({ + appVersion: '6.5.0', + bundleVersion: '1000', + isLegacyInstall: true, + legacyAppVersion: '6.5.0', + }); + expect(upgradedSame.isFirstLaunch()).toBe(false); + expect(upgradedSame.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(upgradedSame.isFirstLaunchForCurrentBundle()).toBe(true); + + const legacyUpgradeStorage = createStorage(); + const upgradedHigher = openDocument(legacyUpgradeStorage); + upgradedHigher.initFirstLaunch({ + appVersion: '6.6.0', + bundleVersion: '1001', + isLegacyInstall: true, + legacyAppVersion: '6.5.0', + }); + expect(upgradedHigher.isFirstLaunch()).toBe(false); + expect(upgradedHigher.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(upgradedHigher.isFirstLaunchForCurrentBundle()).toBe(true); + + const next = openDocument(legacyUpgradeStorage); + next.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1001' }); + expect(next.isFirstLaunch()).toBe(false); + expect(next.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(next.isFirstLaunchForCurrentBundle()).toBe(false); +}); + +it('handles prerelease and numeric version comparisons accurately', () => { + const mod = loadModule(); + expect(mod.compareVersions('6.10.0', '6.5.0')).toBeGreaterThan(0); + expect(mod.compareVersions('6.5.0', '6.5')).toBe(0); + expect(mod.compareVersions('6.5.0', '6.5.0-beta.1')).toBeGreaterThan(0); + expect(mod.compareVersions('6.5.0-beta.2', '6.5.0-beta.1')).toBeGreaterThan(0); + expect(mod.compareVersions('1000', '999')).toBeGreaterThan(0); +}); + +it('does not write markers for missing or malformed identities', () => { + const storage = createStorage(); + const startup = openDocument(storage); + + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(startup.isFirstLaunchForCurrentAppVersion('2.0\n')).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle('../A')).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle('X'.repeat(121))).toBe(false); + expect(storage.getItem).not.toHaveBeenCalled(); + expect(storage.setItem).not.toHaveBeenCalled(); +}); + +it('returns false without browser storage and tolerates blocked reads and writes', () => { + const server = openDocument(); + expect(server.isFirstLaunch()).toBe(false); + expect(server.isFirstLaunchForCurrentAppVersion('2.0')).toBe(false); + expect(server.isFirstLaunchForCurrentBundle('1000')).toBe(false); + + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: { + get localStorage() { + throw new Error('Storage is blocked'); + }, + }, + }); + expect(loadModule().isFirstLaunch()).toBe(false); + + const storage = createStorage(); + storage.setItem.mockImplementationOnce(() => { + throw new Error('Storage is full'); + }); + const startup = openDocument(storage); + expect(startup.isFirstLaunch()).toBe(false); + expect(startup.isFirstLaunch()).toBe(false); + expect(storage.setItem).toHaveBeenCalledTimes(1); +}); diff --git a/native-modules/react-native-device-utils/src/firstLaunch.native.ts b/native-modules/react-native-device-utils/src/firstLaunch.native.ts new file mode 100644 index 000000000..8bc20b926 --- /dev/null +++ b/native-modules/react-native-device-utils/src/firstLaunch.native.ts @@ -0,0 +1,40 @@ +import { ReactNativeDeviceUtils } from './index'; + +export interface FirstLaunchInitOptions { + appVersion?: string; + bundleVersion?: string; + /** + * Used on Web/Desktop/Extension only; on iOS/Android pass legacy signals to + * the native `DeviceUtilsFirstLaunch.initialize(...)` singleton at app launch. + */ + isLegacyInstall?: boolean; + /** + * Used on Web/Desktop/Extension only; on iOS/Android pass legacy signals to + * the native `DeviceUtilsFirstLaunch.initialize(...)` singleton at app launch. + */ + legacyAppVersion?: string; +} + +export function initFirstLaunch(options?: FirstLaunchInitOptions): void { + ReactNativeDeviceUtils.isFirstLaunch(); + ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); + if (options?.bundleVersion !== undefined) { + ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(options.bundleVersion); + } +} + +export function isFirstLaunch(): boolean { + return ReactNativeDeviceUtils.isFirstLaunch(); +} + +export function isFirstLaunchForCurrentAppVersion( + _appVersion?: string +): boolean { + return ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); +} + +export function isFirstLaunchForCurrentBundle( + bundleVersion?: string +): boolean { + return ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(bundleVersion); +} diff --git a/native-modules/react-native-device-utils/src/firstLaunch.web.ts b/native-modules/react-native-device-utils/src/firstLaunch.web.ts new file mode 100644 index 000000000..2bf82f099 --- /dev/null +++ b/native-modules/react-native-device-utils/src/firstLaunch.web.ts @@ -0,0 +1,350 @@ +export interface FirstLaunchInitOptions { + appVersion?: string; + bundleVersion?: string; + /** + * Host-provided signal indicating this storage area already existed + * in a legacy version before first-launch tracking was introduced. + * Ignored once persisted state already exists. + */ + isLegacyInstall?: boolean; + /** + * Optional previous app version known to the host from legacy state. + * Ignored once persisted state already exists. + */ + legacyAppVersion?: string; +} + +interface PersistedFirstLaunchState { + hasLaunched: boolean; + highestAppVersion: string | null; + highestBundleVersion: string | null; +} + +export const FIRST_LAUNCH_STORAGE_KEY = 'onekey:device-utils:first-launch'; +const invalidVersionCharacter = /[^0-9A-Za-z._+-]/; +const digitsOnly = /^[0-9]+$/; + +let cachedFirstLaunch: boolean | undefined; +let cachedAppVersionResult: boolean | undefined; +let cachedAppVersion: string | undefined; +const cachedBundleResults = new Map(); +let lastBundleVersion: string | undefined; + +function isValidVersion(version?: string | null): version is string { + return ( + typeof version === 'string' && + version.length > 0 && + version.length <= 120 && + !invalidVersionCharacter.test(version) + ); +} + +function compareUnsignedIntStrings(a: string, b: string): number { + const normA = a.replace(/^0+/, '') || '0'; + const normB = b.replace(/^0+/, '') || '0'; + if (normA.length !== normB.length) { + return normA.length < normB.length ? -1 : 1; + } + if (normA === normB) { + return 0; + } + return normA < normB ? -1 : 1; +} + +function compareIdentifiers(a: string, b: string): number { + const aNum = digitsOnly.test(a); + const bNum = digitsOnly.test(b); + if (aNum && bNum) { + return compareUnsignedIntStrings(a, b); + } + if (aNum !== bNum) { + return aNum ? -1 : 1; + } + if (a === b) { + return 0; + } + return a < b ? -1 : 1; +} + +export function compareVersions(a: string, b: string): number { + const stripBuild = (v: string) => { + const plusIndex = v.indexOf('+'); + return plusIndex >= 0 ? v.slice(0, plusIndex) : v; + }; + const splitPre = (v: string): [string, string | null] => { + const dashIndex = v.indexOf('-'); + return dashIndex >= 0 + ? [v.slice(0, dashIndex), v.slice(dashIndex + 1)] + : [v, null]; + }; + + const [mainA, preA] = splitPre(stripBuild(a)); + const [mainB, preB] = splitPre(stripBuild(b)); + const segA = mainA.split('.'); + const segB = mainB.split('.'); + const maxLen = Math.max(segA.length, segB.length); + + for (let i = 0; i < maxLen; i += 1) { + const partA = segA[i] ?? '0'; + const partB = segB[i] ?? '0'; + const cmp = compareIdentifiers(partA, partB); + if (cmp !== 0) { + return cmp; + } + } + + if (preA === null && preB === null) { + return 0; + } + if (preA === null) { + return 1; + } + if (preB === null) { + return -1; + } + + const preSegA = preA.split('.'); + const preSegB = preB.split('.'); + const maxPreLen = Math.max(preSegA.length, preSegB.length); + for (let i = 0; i < maxPreLen; i += 1) { + if (i >= preSegA.length) { + return -1; + } + if (i >= preSegB.length) { + return 1; + } + const cmp = compareIdentifiers(preSegA[i]!, preSegB[i]!); + if (cmp !== 0) { + return cmp; + } + } + return 0; +} + +function getStorage(): Storage | null { + if (typeof window === 'undefined') { + return null; + } + try { + return window.localStorage ?? null; + } catch { + return null; + } +} + +function readState( + storage: Storage, + legacyAppVersion?: string +): { + state: PersistedFirstLaunchState; + existed: boolean; +} | null { + try { + const raw = storage.getItem(FIRST_LAUNCH_STORAGE_KEY); + if (raw === null) { + return { + state: { + hasLaunched: false, + highestAppVersion: isValidVersion(legacyAppVersion) + ? legacyAppVersion + : null, + highestBundleVersion: null, + }, + existed: false, + }; + } + const parsed = JSON.parse(raw) as Partial | null; + return { + state: { + hasLaunched: parsed?.hasLaunched === true, + highestAppVersion: isValidVersion(parsed?.highestAppVersion) + ? parsed.highestAppVersion + : null, + highestBundleVersion: isValidVersion(parsed?.highestBundleVersion) + ? parsed.highestBundleVersion + : null, + }, + existed: true, + }; + } catch { + return null; + } +} + +function writeState( + storage: Storage, + state: PersistedFirstLaunchState +): boolean { + try { + storage.setItem(FIRST_LAUNCH_STORAGE_KEY, JSON.stringify(state)); + return true; + } catch { + return false; + } +} + +function ensureFirstLaunch( + isLegacyInstall = false, + legacyAppVersion?: string +): boolean { + if (cachedFirstLaunch !== undefined) { + return cachedFirstLaunch; + } + const storage = getStorage(); + if (!storage) { + cachedFirstLaunch = false; + return false; + } + const loaded = readState(storage, legacyAppVersion); + if (!loaded) { + cachedFirstLaunch = false; + return false; + } + const { state, existed } = loaded; + if (state.hasLaunched) { + cachedFirstLaunch = false; + return false; + } + const nextState: PersistedFirstLaunchState = { + ...state, + hasLaunched: true, + }; + if (!writeState(storage, nextState)) { + cachedFirstLaunch = false; + return false; + } + cachedFirstLaunch = existed ? false : !isLegacyInstall; + return cachedFirstLaunch; +} + +function resolveAppVersion( + appVersion?: string, + isLegacyInstall = false, + legacyAppVersion?: string +): boolean { + if (appVersion === undefined) { + return cachedAppVersionResult ?? false; + } + if (!isValidVersion(appVersion)) { + return false; + } + if (cachedAppVersionResult !== undefined && cachedAppVersion === appVersion) { + return cachedAppVersionResult; + } + ensureFirstLaunch(isLegacyInstall, legacyAppVersion); + const storage = getStorage(); + if (!storage) { + cachedAppVersion = appVersion; + cachedAppVersionResult = false; + return false; + } + const loaded = readState(storage, legacyAppVersion); + if (!loaded) { + cachedAppVersion = appVersion; + cachedAppVersionResult = false; + return false; + } + const { state } = loaded; + const isHigher = + state.highestAppVersion === null || + compareVersions(appVersion, state.highestAppVersion) > 0; + if (isHigher) { + const nextState: PersistedFirstLaunchState = { + ...state, + hasLaunched: true, + highestAppVersion: appVersion, + }; + if (!writeState(storage, nextState)) { + cachedAppVersion = appVersion; + cachedAppVersionResult = false; + return false; + } + } + cachedAppVersion = appVersion; + cachedAppVersionResult = isHigher; + return isHigher; +} + +function resolveBundleVersion( + bundleVersion?: string, + isLegacyInstall = false, + legacyAppVersion?: string +): boolean { + if (bundleVersion === undefined) { + return lastBundleVersion !== undefined + ? (cachedBundleResults.get(lastBundleVersion) ?? false) + : false; + } + if (!isValidVersion(bundleVersion)) { + return false; + } + const cached = cachedBundleResults.get(bundleVersion); + if (cached !== undefined) { + lastBundleVersion = bundleVersion; + return cached; + } + ensureFirstLaunch(isLegacyInstall, legacyAppVersion); + const storage = getStorage(); + if (!storage) { + cachedBundleResults.set(bundleVersion, false); + lastBundleVersion = bundleVersion; + return false; + } + const loaded = readState(storage, legacyAppVersion); + if (!loaded) { + cachedBundleResults.set(bundleVersion, false); + lastBundleVersion = bundleVersion; + return false; + } + const { state } = loaded; + const isHigher = + state.highestBundleVersion === null || + compareVersions(bundleVersion, state.highestBundleVersion) > 0; + if (isHigher) { + const nextState: PersistedFirstLaunchState = { + ...state, + hasLaunched: true, + highestBundleVersion: bundleVersion, + }; + if (!writeState(storage, nextState)) { + cachedBundleResults.set(bundleVersion, false); + lastBundleVersion = bundleVersion; + return false; + } + } + cachedBundleResults.set(bundleVersion, isHigher); + lastBundleVersion = bundleVersion; + return isHigher; +} + +export function initFirstLaunch(options?: FirstLaunchInitOptions): void { + const isLegacyInstall = options?.isLegacyInstall === true; + const legacyAppVersion = options?.legacyAppVersion; + ensureFirstLaunch(isLegacyInstall, legacyAppVersion); + if (options?.appVersion !== undefined) { + resolveAppVersion(options.appVersion, isLegacyInstall, legacyAppVersion); + } + if (options?.bundleVersion !== undefined) { + resolveBundleVersion( + options.bundleVersion, + isLegacyInstall, + legacyAppVersion + ); + } +} + +export function isFirstLaunch(): boolean { + return ensureFirstLaunch(); +} + +export function isFirstLaunchForCurrentAppVersion( + appVersion?: string +): boolean { + return resolveAppVersion(appVersion); +} + +export function isFirstLaunchForCurrentBundle( + bundleVersion?: string +): boolean { + return resolveBundleVersion(bundleVersion); +} diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 02efb49ce..60378eda3 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -139,4 +139,51 @@ fun main() { } check(capacityWinners.get() == 128 && rejectedClaims.get() == 128) println("Kotlin in-memory store: passed") + + val directory = kotlin.io.path.createTempDirectory("device-utils-first-launch-").toFile() + try { + fun launch(version: String, previous: String? = null) = + FirstLaunchHistory(directory, version, previous, hasPreviousLaunch = previous != null) + + val fresh = launch("6.5.0") + check(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) + check(!fresh.isFirstLaunchForBundle(null)) + check(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) + check(fresh.isFirstLaunchForBundle(null)) + check(!fresh.isFirstLaunchForBundle("../escape")) + + val restart = launch("6.5.0") + check(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) + check(!restart.isFirstLaunchForBundle("1000")) + check(!restart.isFirstLaunchForBundle(null)) + check(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) + check(restart.isFirstLaunchForBundle(null)) + + val rollback = launch("6.5.0") + check(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) + check(!rollback.isFirstLaunchForBundle("1000")) + check(!rollback.isFirstLaunchForBundle("999")) + + val upgrade = launch("6.10.0", previous = "6.5.0") + check(!upgrade.isFirstLaunch && upgrade.isFirstLaunchForCurrentAppVersion) + check(!upgrade.isFirstLaunchForBundle("1001")) + check(upgrade.isFirstLaunchForBundle("1002")) + + val downgrade = launch("6.9.0", previous = "6.10.0") + check(!downgrade.isFirstLaunch && !downgrade.isFirstLaunchForCurrentAppVersion) + check(!downgrade.isFirstLaunchForBundle("1001")) + + val legacySame = FirstLaunchHistory(directory.resolve("legacy-same"), "6.5.0", "6.5.0", hasPreviousLaunch = true) + check(!legacySame.isFirstLaunch && !legacySame.isFirstLaunchForCurrentAppVersion) + + val legacyUpgraded = FirstLaunchHistory(directory.resolve("legacy-upgraded"), "6.6.0", "6.5.0", hasPreviousLaunch = true) + check(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + + val file = directory.resolve("file").apply { writeText("") } + val failed = FirstLaunchHistory(file, "6.5.0", null, hasPreviousLaunch = false) + check(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) + } finally { + directory.deleteRecursively() + } + println("Kotlin first launch history: passed") } diff --git a/native-modules/react-native-device-utils/tests/in-memory-store.cjs b/native-modules/react-native-device-utils/tests/in-memory-store.cjs index 9e2d30b31..58da54971 100644 --- a/native-modules/react-native-device-utils/tests/in-memory-store.cjs +++ b/native-modules/react-native-device-utils/tests/in-memory-store.cjs @@ -20,6 +20,7 @@ if (mode !== '--kotlin') { run('swiftc', [ join(root, 'nitrogen/generated/ios/swift/InMemoryValue.swift'), join(root, 'ios/InMemoryStore.swift'), + join(root, 'ios/DeviceUtilsFirstLaunch.swift'), join(__dirname, 'main.swift'), '-module-cache-path', join(output, 'swift-module-cache'), @@ -42,6 +43,7 @@ if (mode !== '--swift') { annotation, join(root, 'nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/InMemoryValue.kt'), join(root, 'android/src/main/java/com/margelo/nitro/reactnativedeviceutils/InMemoryStore.kt'), + join(root, 'android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt'), join(__dirname, 'InMemoryStoreTest.kt'), '-include-runtime', '-d', diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index 9c689d4b8..fa05d707b 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -129,3 +129,69 @@ DispatchQueue.concurrentPerform(iterations: 256) { index in } precondition(capacityWinners == 128 && rejectedClaims == 128) print("Swift in-memory store: passed") + +func testFirstLaunchHistory() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + + func launch(_ version: String, previous: String? = nil) -> FirstLaunchHistory { + FirstLaunchHistory( + directory: directory, + appVersion: version, + previousAppVersion: previous, + hasPreviousLaunch: previous != nil + ) + } + + let fresh = launch("6.5.0") + precondition(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) + precondition(!fresh.isFirstLaunchForBundle(nil)) + precondition(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) + precondition(fresh.isFirstLaunchForBundle(nil)) + precondition(!fresh.isFirstLaunchForBundle("../escape")) + + let restart = launch("6.5.0") + precondition(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) + precondition(!restart.isFirstLaunchForBundle("1000")) + precondition(!restart.isFirstLaunchForBundle(nil)) + precondition(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) + precondition(restart.isFirstLaunchForBundle(nil)) + + let rollback = launch("6.5.0") + precondition(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) + precondition(!rollback.isFirstLaunchForBundle("1000")) + precondition(!rollback.isFirstLaunchForBundle("999")) + + let upgrade = launch("6.10.0", previous: "6.5.0") + precondition(!upgrade.isFirstLaunch && upgrade.isFirstLaunchForCurrentAppVersion) + precondition(!upgrade.isFirstLaunchForBundle("1001")) + precondition(upgrade.isFirstLaunchForBundle("1002")) + + let downgrade = launch("6.9.0", previous: "6.10.0") + precondition(!downgrade.isFirstLaunch && !downgrade.isFirstLaunchForCurrentAppVersion) + precondition(!downgrade.isFirstLaunchForBundle("1001")) + + let legacySameVersion = FirstLaunchHistory( + directory: directory.appendingPathComponent("legacy-same"), + appVersion: "6.5.0", + previousAppVersion: "6.5.0", + hasPreviousLaunch: true + ) + precondition(!legacySameVersion.isFirstLaunch && !legacySameVersion.isFirstLaunchForCurrentAppVersion) + + let legacyUpgraded = FirstLaunchHistory( + directory: directory.appendingPathComponent("legacy-upgraded"), + appVersion: "6.6.0", + previousAppVersion: "6.5.0", + hasPreviousLaunch: true + ) + precondition(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + + let file = directory.appendingPathComponent("file") + try Data().write(to: file) + let failed = FirstLaunchHistory(directory: file, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + precondition(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) +} + +try testFirstLaunchHistory() +print("Swift first launch history: passed") diff --git a/native-modules/react-native-device-utils/tsconfig.json b/native-modules/react-native-device-utils/tsconfig.json index 604e2a148..0fd68c6e4 100644 --- a/native-modules/react-native-device-utils/tsconfig.json +++ b/native-modules/react-native-device-utils/tsconfig.json @@ -10,7 +10,7 @@ "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "jsx": "react-jsx", - "lib": ["ESNext"], + "lib": ["ESNext", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "noEmit": true, From 334696da357f776982d68da382e25c719167cf21 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 16:03:58 +0800 Subject: [PATCH 2/7] fix(device-utils): address first-launch PR review findings --- .../react-native-device-utils/README.md | 2 +- .../FirstLaunchHistory.kt | 202 +++++++++++--- .../react-native-device-utils/docs/SPEC.md | 8 +- .../ios/DeviceUtilsFirstLaunch.swift | 51 ++-- .../react-native-device-utils/package.json | 4 +- .../src/__tests__/firstLaunch.test.ts | 134 +++++---- .../src/firstLaunch.web.ts | 254 +++++++++++------- .../tests/InMemoryStoreTest.kt | 25 +- .../tests/main.swift | 19 +- 9 files changed, 489 insertions(+), 210 deletions(-) diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index 88b332cb1..f57696593 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -109,7 +109,7 @@ const firstBundleLaunch = isFirstLaunchForCurrentBundle(); On iOS and Android, initialize the pure native singleton early in `AppDelegate.didFinishLaunchingWithOptions` (`OneKeyDeviceUtilsFirstLaunch` via -`initializeWithOptions:` / `hasPersistedState`) or `Application.onCreate()` +`initializeWithOptions:` / `hasPersistedStateNumber`) or `Application.onCreate()` (`DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... })`) so host-specific legacy upgrade detection stays in the app and runs before React Native starts. diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt index 52fad2447..0a47931e0 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -1,6 +1,7 @@ package com.margelo.nitro.reactnativedeviceutils import java.io.File +import java.io.FileOutputStream import java.io.IOException internal class FirstLaunchHistory( @@ -22,7 +23,7 @@ internal class FirstLaunchHistory( private var persisted: PersistedState private val storageAvailable: Boolean private val bundleResults = mutableMapOf() - private var lastBundleVersion: String? = null + private var initialBundleVersion: String? = null init { val validPrevious = validatedVersion(previousAppVersion) @@ -88,16 +89,17 @@ internal class FirstLaunchHistory( @Synchronized fun isFirstLaunchForBundle(bundleVersion: String?): Boolean { if (bundleVersion == null) { - return lastBundleVersion?.let { bundleResults[it] } ?: false + return initialBundleVersion?.let { bundleResults[it] } ?: false } val validBundle = validatedVersion(bundleVersion) ?: return false + if (initialBundleVersion == null) { + initialBundleVersion = validBundle + } bundleResults[validBundle]?.let { - lastBundleVersion = validBundle return it } if (!storageAvailable) { bundleResults[validBundle] = false - lastBundleVersion = validBundle return false } val baseline = persisted.highestBundleVersion @@ -106,13 +108,11 @@ internal class FirstLaunchHistory( val next = persisted.copy(highestBundleVersion = validBundle) if (!writeState(next)) { bundleResults[validBundle] = false - lastBundleVersion = validBundle return false } persisted = next } bundleResults[validBundle] = isHigher - lastBundleVersion = validBundle return isHigher } @@ -120,18 +120,7 @@ internal class FirstLaunchHistory( if (!file.isFile) { null } else { - val text = file.readText(Charsets.UTF_8) - val hasLaunched = Regex(""""hasLaunched"\s*:\s*(true|false)""") - .find(text)?.groupValues?.get(1) == "true" - val highestApp = Regex(""""highestAppVersion"\s*:\s*"([^"]*)"""") - .find(text)?.groupValues?.get(1)?.let(::validatedVersion) - val highestBundle = Regex(""""highestBundleVersion"\s*:\s*"([^"]*)"""") - .find(text)?.groupValues?.get(1)?.let(::validatedVersion) - PersistedState( - hasLaunched = hasLaunched, - highestAppVersion = highestApp, - highestBundleVersion = highestBundle, - ) + parsePersistedJson(file.readText(Charsets.UTF_8)) } } catch (_: IOException) { null @@ -139,36 +128,175 @@ internal class FirstLaunchHistory( null } - private fun writeState(state: PersistedState): Boolean = try { - if (!directory.exists() && !directory.mkdirs() && !directory.isDirectory) { + private fun writeState(state: PersistedState): Boolean { + var temp: File? = null + return try { + if (!directory.exists() && !directory.mkdirs() && !directory.isDirectory) { + false + } else if (!directory.isDirectory) { + false + } else { + val appJson = state.highestAppVersion?.let { "\"$it\"" } ?: "null" + val bundleJson = state.highestBundleVersion?.let { "\"$it\"" } ?: "null" + val json = + """{"hasLaunched":${state.hasLaunched},"highestAppVersion":$appJson,"highestBundleVersion":$bundleJson}""" + temp = File.createTempFile("${stateFile.name}.", ".tmp", directory) + FileOutputStream(temp).use { fos -> + fos.write(json.toByteArray(Charsets.UTF_8)) + fos.fd.sync() + } + if (temp.renameTo(stateFile)) { + temp = null + true + } else { + false + } + } + } catch (_: IOException) { false - } else if (!directory.isDirectory) { + } catch (_: SecurityException) { false - } else { - val appJson = state.highestAppVersion?.let { "\"$it\"" } ?: "null" - val bundleJson = state.highestBundleVersion?.let { "\"$it\"" } ?: "null" - val json = - """{"hasLaunched":${state.hasLaunched},"highestAppVersion":$appJson,"highestBundleVersion":$bundleJson}""" - val temp = File(directory, "${stateFile.name}.tmp") - temp.writeText(json, Charsets.UTF_8) - if (!temp.renameTo(stateFile)) { - stateFile.writeText(json, Charsets.UTF_8) - temp.delete() + } finally { + temp?.delete() + } + } + + private fun parsePersistedJson(raw: String): PersistedState? { + var pos = 0 + val len = raw.length + + fun skipWs() { + while (pos < len && raw[pos] in " \t\r\n") pos++ + } + + fun readString(): String? { + if (pos >= len || raw[pos] != '"') return null + pos++ + val sb = StringBuilder() + while (pos < len) { + val c = raw[pos++] + when { + c == '"' -> return sb.toString() + c == '\\' -> { + if (pos >= len) return null + val esc = raw[pos++] + when (esc) { + '"', '\\', '/' -> sb.append(esc) + 'b' -> sb.append('\b') + 'f' -> sb.append('\u000C') + 'n' -> sb.append('\n') + 'r' -> sb.append('\r') + 't' -> sb.append('\t') + 'u' -> { + if (pos + 4 > len) return null + val hex = raw.substring(pos, pos + 4) + val code = hex.toIntOrNull(16) ?: return null + sb.append(code.toChar()) + pos += 4 + } + else -> return null + } + } + c.code < 0x20 -> return null + else -> sb.append(c) + } } - true + return null } - } catch (_: IOException) { - false - } catch (_: SecurityException) { - false + + fun readLiteral(expected: String): Boolean { + if (raw.regionMatches(pos, expected, 0, expected.length)) { + pos += expected.length + return true + } + return false + } + + skipWs() + if (pos >= len || raw[pos] != '{') return null + pos++ + skipWs() + + var hasLaunched: Boolean? = null + var highestAppVersion: String? = null + var highestBundleVersion: String? = null + var sawAppKey = false + var sawBundleKey = false + + if (pos < len && raw[pos] == '}') { + // Missing required hasLaunched field. + return null + } + + while (true) { + skipWs() + val key = readString() ?: return null + skipWs() + if (pos >= len || raw[pos] != ':') return null + pos++ + skipWs() + when (key) { + "hasLaunched" -> { + if (hasLaunched != null) return null + hasLaunched = when { + readLiteral("true") -> true + readLiteral("false") -> false + else -> return null + } + } + "highestAppVersion" -> { + if (sawAppKey) return null + sawAppKey = true + highestAppVersion = if (readLiteral("null")) { + null + } else { + val s = readString() ?: return null + validatedVersion(s) ?: return null + } + } + "highestBundleVersion" -> { + if (sawBundleKey) return null + sawBundleKey = true + highestBundleVersion = if (readLiteral("null")) { + null + } else { + val s = readString() ?: return null + validatedVersion(s) ?: return null + } + } + else -> return null + } + skipWs() + if (pos >= len) return null + when (raw[pos]) { + ',' -> pos++ + '}' -> { + pos++ + break + } + else -> return null + } + } + + skipWs() + if (pos != len) return null + val resolvedHasLaunched = hasLaunched ?: return null + return PersistedState( + hasLaunched = resolvedHasLaunched, + highestAppVersion = highestAppVersion, + highestBundleVersion = highestBundleVersion, + ) } companion object { internal const val FILE_NAME = "onekey-device-utils-first-launch.json" + private val VERSION_REGEX = + Regex("""^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$""") + internal fun validatedVersion(version: String?): String? { if (version == null || version.length !in 1..120) return null - if (!version.all { it in '0'..'9' || it in 'A'..'Z' || it in 'a'..'z' || it in "._-+" }) return null + if (!VERSION_REGEX.matches(version)) return null return version } diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index f31d20205..c3b6ac80d 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -31,13 +31,13 @@ On each launch, the startup path performs a single **read persisted state → co | Platform | Initialization | Storage | Legacy-install evidence | | --- | --- | --- | --- | -| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in Application Support | Owned by the host app. Use `hasPersistedState()` to skip legacy checks once persisted state exists. | +| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in Application Support | Owned by the host app. Use `hasPersistedState()` (or `hasPersistedStateNumber` returning `NSNumber` for `perform(_:)`) to skip legacy checks once persisted state exists. | | Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in `context.filesDir` | Owned by the host app (lambdas are only invoked when no persisted file exists yet). | -| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` at UI startup. | `localStorage` key `onekey:device-utils:first-launch` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | +| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` once at UI startup before reading getters. | `localStorage` key `onekey:device-utils:first-launch` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | -Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted field. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. +Version strings must have a numeric dot-separated core with optional SemVer pre-release (`-...`) and build metadata (`+...`) suffixes (1–120 ASCII chars, e.g. `6.5.0`, `6.5.0-beta.1`, `1000`). Non-numeric cores such as `v6.5.0` are rejected. Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted field. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. -Missing startup initialization, unavailable or corrupted storage, invalid identifiers (must be 1–120 ASCII `[0-9A-Za-z._+-]`), and write failures fail safe and return `false`. There are no network calls, JS callbacks, async waits, or wallet reads. Native app-install and app-version state are recorded during native startup even if JavaScript never calls a getter. Call `initFirstLaunch({ appVersion, bundleVersion })` at app JS startup so bundle versions on native and all three dimensions on Web/Desktop/Extension are recorded unconditionally. +Missing startup initialization, unavailable or corrupted storage (malformed JSON, wrong field types, or invalid stored version strings), invalid identifiers, and write failures fail closed and return `false` without overwriting the damaged record. Zero-argument getters remain bound to the startup identities and are unaffected by later explicit version lookups. On Web/Desktop/Extension, `initFirstLaunch(...)` commits the startup snapshot in a single synchronous `localStorage.setItem`; getters called before `initFirstLaunch(...)` return `false` without touching storage. Because synchronous Web Storage has no cross-document lock, simultaneous first loads across two separate tabs may both observe an absent key. ## Web, desktop renderer, and extension pages diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index ac97e0f86..539589725 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -6,14 +6,19 @@ public final class DeviceUtilsFirstLaunch: NSObject { private static var history: FirstLaunchHistory? /// Returns true if the persisted first-launch state file already exists on disk. - /// Safe to call via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` before - /// running host-specific legacy upgrade checks. - @objc public static func hasPersistedState() -> Bool { + public static func hasPersistedState() -> Bool { guard let directory = defaultDirectory() else { return false } let fileURL = directory.appendingPathComponent(FirstLaunchHistory.fileName) return FileManager.default.fileExists(atPath: fileURL.path) } + /// Object-returning variant of `hasPersistedState()` safe for dynamic invocation + /// via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `perform(_:)`. + @objc(hasPersistedStateNumber) + public static func hasPersistedStateNumber() -> NSNumber { + NSNumber(value: hasPersistedState()) + } + /// Initializes the process-wide first-launch state from the host app (e.g. AppDelegate). /// Accepts an Objective-C `NSDictionary` so Swift hosts can invoke it dynamically via /// `NSClassFromString` + `perform(_:with:)` without importing Nitro C++ headers. @@ -95,7 +100,7 @@ final class FirstLaunchHistory { private var persisted: PersistedState private var storageAvailable: Bool private var bundleResults: [String: Bool] = [:] - private var lastBundleVersion: String? + private var initialBundleVersion: String? init(directory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { fileURL = directory.appendingPathComponent(Self.fileName) @@ -159,18 +164,19 @@ final class FirstLaunchHistory { func isFirstLaunchForBundle(_ bundleVersion: String?) -> Bool { guard let bundleVersion else { - return lastBundleVersion.flatMap { bundleResults[$0] } ?? false + return initialBundleVersion.flatMap { bundleResults[$0] } ?? false } guard let validBundle = Self.validatedVersion(bundleVersion) else { return false } + if initialBundleVersion == nil { + initialBundleVersion = validBundle + } if let cached = bundleResults[validBundle] { - lastBundleVersion = validBundle return cached } guard storageAvailable else { bundleResults[validBundle] = false - lastBundleVersion = validBundle return false } let baseline = persisted.highestBundleVersion @@ -180,13 +186,11 @@ final class FirstLaunchHistory { next.highestBundleVersion = validBundle guard Self.writeState(next, to: fileURL, directory: fileURL.deletingLastPathComponent()) else { bundleResults[validBundle] = false - lastBundleVersion = validBundle return false } persisted = next } bundleResults[validBundle] = isHigher - lastBundleVersion = validBundle return isHigher } @@ -263,24 +267,31 @@ final class FirstLaunchHistory { } } - private static func validatedVersion(_ version: String?) -> String? { - guard let version, (1...120).contains(version.utf8.count), - version.utf8.allSatisfy({ - switch $0 { - case 43, 45, 46, 48...57, 65...90, 95, 97...122: return true - default: return false - } - }) else { return nil } + static func validatedVersion(_ version: String?) -> String? { + guard let version, (1...120).contains(version.utf8.count) else { return nil } + let fullRange = NSRange(version.startIndex.. PersistedState? { guard let data = try? Data(contentsOf: url), - var decoded = try? JSONDecoder().decode(PersistedState.self, from: data) else { + let decoded = try? JSONDecoder().decode(PersistedState.self, from: data) else { + return nil + } + if let app = decoded.highestAppVersion, validatedVersion(app) == nil { + return nil + } + if let bundle = decoded.highestBundleVersion, validatedVersion(bundle) == nil { return nil } - decoded.highestAppVersion = validatedVersion(decoded.highestAppVersion) - decoded.highestBundleVersion = validatedVersion(decoded.highestBundleVersion) return decoded } diff --git a/native-modules/react-native-device-utils/package.json b/native-modules/react-native-device-utils/package.json index f5cc4b1e1..8d4f166f1 100644 --- a/native-modules/react-native-device-utils/package.json +++ b/native-modules/react-native-device-utils/package.json @@ -11,15 +11,17 @@ "default": "./lib/module/index.js" }, "./first-launch": { - "types": "./lib/typescript/src/firstLaunch.web.d.ts", "browser": { + "types": "./lib/typescript/src/firstLaunch.web.d.ts", "source": "./src/firstLaunch.web.ts", "default": "./lib/module/firstLaunch.web.js" }, "react-native": { + "types": "./lib/typescript/src/firstLaunch.native.d.ts", "source": "./src/firstLaunch.native.ts", "default": "./lib/module/firstLaunch.native.js" }, + "types": "./lib/typescript/src/firstLaunch.web.d.ts", "source": "./src/firstLaunch.web.ts", "default": "./lib/module/firstLaunch.web.js" }, diff --git a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts index f95184abd..106acddb3 100644 --- a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts +++ b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts @@ -46,11 +46,12 @@ afterEach(() => { } }); -it('records installation, highest app version, and highest bundle version via initFirstLaunch', () => { +it('records installation, highest app version, and highest bundle version in a single write', () => { const storage = createStorage(); const startup = openDocument(storage); startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(storage.setItem).toHaveBeenCalledTimes(1); expect(startup.isFirstLaunch()).toBe(true); expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); @@ -58,16 +59,25 @@ it('records installation, highest app version, and highest bundle version via in expect(startup.isFirstLaunch()).toBe(true); expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); + expect(storage.setItem).toHaveBeenCalledTimes(1); + + // Explicit lookup of another identity must not overwrite startup zero-arg results or evict startup cache. + expect(startup.isFirstLaunchForCurrentAppVersion('6.6.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('999')).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); + expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); const reload = openDocument(storage); - reload.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + reload.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1000' }); expect(reload.isFirstLaunch()).toBe(false); expect(reload.isFirstLaunchForCurrentAppVersion()).toBe(false); expect(reload.isFirstLaunchForCurrentBundle()).toBe(false); // Higher bundle only const ota = openDocument(storage); - ota.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1001' }); + ota.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1001' }); expect(ota.isFirstLaunch()).toBe(false); expect(ota.isFirstLaunchForCurrentAppVersion()).toBe(false); expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); @@ -75,12 +85,12 @@ it('records installation, highest app version, and highest bundle version via in // Rollback to lower bundle returns false and preserves highestBundleVersion const rollback = openDocument(storage); - rollback.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + rollback.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1000' }); expect(rollback.isFirstLaunch()).toBe(false); expect(rollback.isFirstLaunchForCurrentAppVersion()).toBe(false); expect(rollback.isFirstLaunchForCurrentBundle()).toBe(false); - // Upgrade app version (6.10.0 > 6.5.0 numerically) with same bundle + // Upgrade app version (6.10.0 > 6.6.0 numerically) with same bundle const upgrade = openDocument(storage); upgrade.initFirstLaunch({ appVersion: '6.10.0', bundleVersion: '1001' }); expect(upgrade.isFirstLaunch()).toBe(false); @@ -95,8 +105,28 @@ it('records installation, highest app version, and highest bundle version via in expect(downgrade.isFirstLaunchForCurrentBundle()).toBe(false); }); +it('does not touch storage before initFirstLaunch so legacy init is never consumed early', () => { + const storage = createStorage(); + const doc = openDocument(storage); + + expect(doc.isFirstLaunch()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle('1000')).toBe(false); + expect(storage.getItem).not.toHaveBeenCalled(); + expect(storage.setItem).not.toHaveBeenCalled(); + + doc.initFirstLaunch({ + appVersion: '6.5.0', + bundleVersion: '1000', + isLegacyInstall: true, + legacyAppVersion: '6.5.0', + }); + expect(doc.isFirstLaunch()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle()).toBe(true); +}); + it('honors host-provided legacy upgrade flags without guessing from unrelated keys', () => { - // Unrelated third-party keys in localStorage should NOT trigger legacy detection on their own. const thirdPartyStorage = createStorage({ 'third-party-sdk': '1' }); const freshWithNoise = openDocument(thirdPartyStorage); freshWithNoise.initFirstLaunch({ @@ -105,19 +135,6 @@ it('honors host-provided legacy upgrade flags without guessing from unrelated ke }); expect(freshWithNoise.isFirstLaunch()).toBe(true); - // Host explicitly signals legacy install + previous version. - const legacyStorage = createStorage(); - const upgradedSame = openDocument(legacyStorage); - upgradedSame.initFirstLaunch({ - appVersion: '6.5.0', - bundleVersion: '1000', - isLegacyInstall: true, - legacyAppVersion: '6.5.0', - }); - expect(upgradedSame.isFirstLaunch()).toBe(false); - expect(upgradedSame.isFirstLaunchForCurrentAppVersion()).toBe(false); - expect(upgradedSame.isFirstLaunchForCurrentBundle()).toBe(true); - const legacyUpgradeStorage = createStorage(); const upgradedHigher = openDocument(legacyUpgradeStorage); upgradedHigher.initFirstLaunch({ @@ -129,41 +146,59 @@ it('honors host-provided legacy upgrade flags without guessing from unrelated ke expect(upgradedHigher.isFirstLaunch()).toBe(false); expect(upgradedHigher.isFirstLaunchForCurrentAppVersion()).toBe(true); expect(upgradedHigher.isFirstLaunchForCurrentBundle()).toBe(true); - - const next = openDocument(legacyUpgradeStorage); - next.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1001' }); - expect(next.isFirstLaunch()).toBe(false); - expect(next.isFirstLaunchForCurrentAppVersion()).toBe(false); - expect(next.isFirstLaunchForCurrentBundle()).toBe(false); }); -it('handles prerelease and numeric version comparisons accurately', () => { - const mod = loadModule(); - expect(mod.compareVersions('6.10.0', '6.5.0')).toBeGreaterThan(0); - expect(mod.compareVersions('6.5.0', '6.5')).toBe(0); - expect(mod.compareVersions('6.5.0', '6.5.0-beta.1')).toBeGreaterThan(0); - expect(mod.compareVersions('6.5.0-beta.2', '6.5.0-beta.1')).toBeGreaterThan(0); - expect(mod.compareVersions('1000', '999')).toBeGreaterThan(0); +it('fails closed and preserves storage when persisted history is corrupted', () => { + const corruptPayloads = [ + '', + 'not-json', + 'null', + '{}', + '[]', + JSON.stringify({ hasLaunched: 'yes' }), + JSON.stringify({ hasLaunched: true, highestAppVersion: 23 }), + JSON.stringify({ hasLaunched: true, highestAppVersion: '6.6.0!' }), + JSON.stringify({ hasLaunched: true, highestBundleVersion: 'v1000' }), + ]; + + for (const payload of corruptPayloads) { + const storage = createStorage({ + 'onekey:device-utils:first-launch': payload, + }); + const doc = openDocument(storage); + doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(doc.isFirstLaunch()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle()).toBe(false); + expect(storage.setItem).not.toHaveBeenCalled(); + } }); -it('does not write markers for missing or malformed identities', () => { +it('validates numeric version core and handles prerelease comparisons accurately', () => { const storage = createStorage(); - const startup = openDocument(storage); - - expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(false); - expect(startup.isFirstLaunchForCurrentAppVersion('2.0\n')).toBe(false); - expect(startup.isFirstLaunchForCurrentBundle()).toBe(false); - expect(startup.isFirstLaunchForCurrentBundle('../A')).toBe(false); - expect(startup.isFirstLaunchForCurrentBundle('X'.repeat(121))).toBe(false); - expect(storage.getItem).not.toHaveBeenCalled(); - expect(storage.setItem).not.toHaveBeenCalled(); + const doc = openDocument(storage); + doc.initFirstLaunch({ appVersion: 'v6.5.0', bundleVersion: '../1000' }); + expect(doc.isFirstLaunch()).toBe(true); + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(doc.isFirstLaunchForCurrentBundle()).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('v6.5.0')).toBe(false); + expect(doc.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); + + expect(doc.compareVersions('6.10.0', '6.5.0')).toBeGreaterThan(0); + expect(doc.compareVersions('6.5.0', '6.5')).toBe(0); + expect(doc.compareVersions('6.5.0', '6.5.0-beta.1')).toBeGreaterThan(0); + expect(doc.compareVersions('6.5.0-beta.2', '6.5.0-beta.1')).toBeGreaterThan( + 0 + ); + expect(doc.compareVersions('1000', '999')).toBeGreaterThan(0); }); -it('returns false without browser storage and tolerates blocked reads and writes', () => { +it('returns false without browser storage and fails closed on write errors', () => { const server = openDocument(); + server.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); expect(server.isFirstLaunch()).toBe(false); - expect(server.isFirstLaunchForCurrentAppVersion('2.0')).toBe(false); - expect(server.isFirstLaunchForCurrentBundle('1000')).toBe(false); + expect(server.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(server.isFirstLaunchForCurrentBundle()).toBe(false); Object.defineProperty(globalThis, 'window', { configurable: true, @@ -173,14 +208,19 @@ it('returns false without browser storage and tolerates blocked reads and writes }, }, }); - expect(loadModule().isFirstLaunch()).toBe(false); + const blocked = loadModule(); + blocked.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); + expect(blocked.isFirstLaunch()).toBe(false); + // If the single startup commit throws, all three startup flags must be false. const storage = createStorage(); storage.setItem.mockImplementationOnce(() => { throw new Error('Storage is full'); }); const startup = openDocument(storage); + startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); expect(startup.isFirstLaunch()).toBe(false); - expect(startup.isFirstLaunch()).toBe(false); + expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(startup.isFirstLaunchForCurrentBundle()).toBe(false); expect(storage.setItem).toHaveBeenCalledTimes(1); }); diff --git a/native-modules/react-native-device-utils/src/firstLaunch.web.ts b/native-modules/react-native-device-utils/src/firstLaunch.web.ts index 2bf82f099..21bdfe808 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.web.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.web.ts @@ -21,21 +21,24 @@ interface PersistedFirstLaunchState { } export const FIRST_LAUNCH_STORAGE_KEY = 'onekey:device-utils:first-launch'; -const invalidVersionCharacter = /[^0-9A-Za-z._+-]/; +const validVersionPattern = + /^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; const digitsOnly = /^[0-9]+$/; -let cachedFirstLaunch: boolean | undefined; -let cachedAppVersionResult: boolean | undefined; -let cachedAppVersion: string | undefined; +let initialized = false; +let storageAvailable = false; +let cachedFirstLaunch = false; +let startupAppVersion: string | undefined; +let startupBundleVersion: string | undefined; +const cachedAppResults = new Map(); const cachedBundleResults = new Map(); -let lastBundleVersion: string | undefined; -function isValidVersion(version?: string | null): version is string { +function isValidVersion(version?: unknown): version is string { return ( typeof version === 'string' && version.length > 0 && version.length <= 120 && - !invalidVersionCharacter.test(version) + validVersionPattern.test(version) ); } @@ -132,6 +135,18 @@ function getStorage(): Storage | null { } } +function parseOptionalVersionField( + value: unknown +): { ok: true; value: string | null } | { ok: false } { + if (value === undefined || value === null) { + return { ok: true, value: null }; + } + if (isValidVersion(value)) { + return { ok: true, value }; + } + return { ok: false }; +} + function readState( storage: Storage, legacyAppVersion?: string @@ -153,16 +168,28 @@ function readState( existed: false, }; } - const parsed = JSON.parse(raw) as Partial | null; + const parsed: unknown = JSON.parse(raw); + if ( + typeof parsed !== 'object' || + parsed === null || + Array.isArray(parsed) + ) { + return null; + } + const record = parsed as Record; + if (typeof record.hasLaunched !== 'boolean') { + return null; + } + const appField = parseOptionalVersionField(record.highestAppVersion); + const bundleField = parseOptionalVersionField(record.highestBundleVersion); + if (!appField.ok || !bundleField.ok) { + return null; + } return { state: { - hasLaunched: parsed?.hasLaunched === true, - highestAppVersion: isValidVersion(parsed?.highestAppVersion) - ? parsed.highestAppVersion - : null, - highestBundleVersion: isValidVersion(parsed?.highestBundleVersion) - ? parsed.highestBundleVersion - : null, + hasLaunched: record.hasLaunched, + highestAppVersion: appField.value, + highestBundleVersion: bundleField.value, }, existed: true, }; @@ -183,65 +210,130 @@ function writeState( } } -function ensureFirstLaunch( - isLegacyInstall = false, - legacyAppVersion?: string -): boolean { - if (cachedFirstLaunch !== undefined) { - return cachedFirstLaunch; +export function initFirstLaunch(options?: FirstLaunchInitOptions): void { + if (initialized) { + return; } + initialized = true; + + const validAppVersion = isValidVersion(options?.appVersion) + ? options.appVersion + : undefined; + const validBundleVersion = isValidVersion(options?.bundleVersion) + ? options.bundleVersion + : undefined; + startupAppVersion = validAppVersion; + startupBundleVersion = validBundleVersion; + + const failClosed = () => { + storageAvailable = false; + cachedFirstLaunch = false; + if (validAppVersion !== undefined) { + cachedAppResults.set(validAppVersion, false); + } + if (validBundleVersion !== undefined) { + cachedBundleResults.set(validBundleVersion, false); + } + }; + const storage = getStorage(); if (!storage) { - cachedFirstLaunch = false; - return false; + failClosed(); + return; } - const loaded = readState(storage, legacyAppVersion); + + const isLegacyInstall = options?.isLegacyInstall === true; + const loaded = readState(storage, options?.legacyAppVersion); if (!loaded) { - cachedFirstLaunch = false; - return false; + failClosed(); + return; } + const { state, existed } = loaded; - if (state.hasLaunched) { - cachedFirstLaunch = false; - return false; + const nextState: PersistedFirstLaunchState = { ...state }; + let needsWrite = !existed; + + const computedFirstLaunch = !state.hasLaunched && !isLegacyInstall; + if (!state.hasLaunched) { + nextState.hasLaunched = true; + needsWrite = true; } - const nextState: PersistedFirstLaunchState = { - ...state, - hasLaunched: true, - }; - if (!writeState(storage, nextState)) { - cachedFirstLaunch = false; + + let computedAppVersion = false; + if (validAppVersion !== undefined) { + computedAppVersion = + nextState.highestAppVersion === null || + compareVersions(validAppVersion, nextState.highestAppVersion) > 0; + if (computedAppVersion) { + nextState.highestAppVersion = validAppVersion; + needsWrite = true; + } + } + + let computedBundleVersion = false; + if (validBundleVersion !== undefined) { + computedBundleVersion = + nextState.highestBundleVersion === null || + compareVersions(validBundleVersion, nextState.highestBundleVersion) > 0; + if (computedBundleVersion) { + nextState.highestBundleVersion = validBundleVersion; + needsWrite = true; + } + } + + if (needsWrite && !writeState(storage, nextState)) { + failClosed(); + return; + } + + storageAvailable = true; + cachedFirstLaunch = computedFirstLaunch; + if (validAppVersion !== undefined) { + cachedAppResults.set(validAppVersion, computedAppVersion); + } + if (validBundleVersion !== undefined) { + cachedBundleResults.set(validBundleVersion, computedBundleVersion); + } +} + +export function isFirstLaunch(): boolean { + if (!initialized) { return false; } - cachedFirstLaunch = existed ? false : !isLegacyInstall; return cachedFirstLaunch; } -function resolveAppVersion( - appVersion?: string, - isLegacyInstall = false, - legacyAppVersion?: string +export function isFirstLaunchForCurrentAppVersion( + appVersion?: string ): boolean { + if (!initialized) { + return false; + } if (appVersion === undefined) { - return cachedAppVersionResult ?? false; + return startupAppVersion !== undefined + ? (cachedAppResults.get(startupAppVersion) ?? false) + : false; } if (!isValidVersion(appVersion)) { return false; } - if (cachedAppVersionResult !== undefined && cachedAppVersion === appVersion) { - return cachedAppVersionResult; + const cached = cachedAppResults.get(appVersion); + if (cached !== undefined) { + return cached; + } + if (!storageAvailable) { + cachedAppResults.set(appVersion, false); + return false; } - ensureFirstLaunch(isLegacyInstall, legacyAppVersion); const storage = getStorage(); if (!storage) { - cachedAppVersion = appVersion; - cachedAppVersionResult = false; + cachedAppResults.set(appVersion, false); return false; } - const loaded = readState(storage, legacyAppVersion); + const loaded = readState(storage); if (!loaded) { - cachedAppVersion = appVersion; - cachedAppVersionResult = false; + storageAvailable = false; + cachedAppResults.set(appVersion, false); return false; } const { state } = loaded; @@ -255,24 +347,23 @@ function resolveAppVersion( highestAppVersion: appVersion, }; if (!writeState(storage, nextState)) { - cachedAppVersion = appVersion; - cachedAppVersionResult = false; + cachedAppResults.set(appVersion, false); return false; } } - cachedAppVersion = appVersion; - cachedAppVersionResult = isHigher; + cachedAppResults.set(appVersion, isHigher); return isHigher; } -function resolveBundleVersion( - bundleVersion?: string, - isLegacyInstall = false, - legacyAppVersion?: string +export function isFirstLaunchForCurrentBundle( + bundleVersion?: string ): boolean { + if (!initialized) { + return false; + } if (bundleVersion === undefined) { - return lastBundleVersion !== undefined - ? (cachedBundleResults.get(lastBundleVersion) ?? false) + return startupBundleVersion !== undefined + ? (cachedBundleResults.get(startupBundleVersion) ?? false) : false; } if (!isValidVersion(bundleVersion)) { @@ -280,20 +371,21 @@ function resolveBundleVersion( } const cached = cachedBundleResults.get(bundleVersion); if (cached !== undefined) { - lastBundleVersion = bundleVersion; return cached; } - ensureFirstLaunch(isLegacyInstall, legacyAppVersion); + if (!storageAvailable) { + cachedBundleResults.set(bundleVersion, false); + return false; + } const storage = getStorage(); if (!storage) { cachedBundleResults.set(bundleVersion, false); - lastBundleVersion = bundleVersion; return false; } - const loaded = readState(storage, legacyAppVersion); + const loaded = readState(storage); if (!loaded) { + storageAvailable = false; cachedBundleResults.set(bundleVersion, false); - lastBundleVersion = bundleVersion; return false; } const { state } = loaded; @@ -308,43 +400,9 @@ function resolveBundleVersion( }; if (!writeState(storage, nextState)) { cachedBundleResults.set(bundleVersion, false); - lastBundleVersion = bundleVersion; return false; } } cachedBundleResults.set(bundleVersion, isHigher); - lastBundleVersion = bundleVersion; return isHigher; } - -export function initFirstLaunch(options?: FirstLaunchInitOptions): void { - const isLegacyInstall = options?.isLegacyInstall === true; - const legacyAppVersion = options?.legacyAppVersion; - ensureFirstLaunch(isLegacyInstall, legacyAppVersion); - if (options?.appVersion !== undefined) { - resolveAppVersion(options.appVersion, isLegacyInstall, legacyAppVersion); - } - if (options?.bundleVersion !== undefined) { - resolveBundleVersion( - options.bundleVersion, - isLegacyInstall, - legacyAppVersion - ); - } -} - -export function isFirstLaunch(): boolean { - return ensureFirstLaunch(); -} - -export function isFirstLaunchForCurrentAppVersion( - appVersion?: string -): boolean { - return resolveAppVersion(appVersion); -} - -export function isFirstLaunchForCurrentBundle( - bundleVersion?: string -): boolean { - return resolveBundleVersion(bundleVersion); -} diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 60378eda3..75b4f3c6e 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -150,6 +150,11 @@ fun main() { check(!fresh.isFirstLaunchForBundle(null)) check(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) check(fresh.isFirstLaunchForBundle(null)) + // Explicit lookup of another bundle must not overwrite zero-arg startup bundle result. + check(!fresh.isFirstLaunchForBundle("999")) + check(fresh.isFirstLaunchForBundle(null)) + // Reject non-numeric version core and traversal strings. + check(!fresh.isFirstLaunchForBundle("v1000")) check(!fresh.isFirstLaunchForBundle("../escape")) val restart = launch("6.5.0") @@ -157,7 +162,7 @@ fun main() { check(!restart.isFirstLaunchForBundle("1000")) check(!restart.isFirstLaunchForBundle(null)) check(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) - check(restart.isFirstLaunchForBundle(null)) + check(!restart.isFirstLaunchForBundle(null)) val rollback = launch("6.5.0") check(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) @@ -179,6 +184,24 @@ fun main() { val legacyUpgraded = FirstLaunchHistory(directory.resolve("legacy-upgraded"), "6.6.0", "6.5.0", hasPreviousLaunch = true) check(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + // Corrupted files (empty, invalid JSON, wrong types, invalid version string) must fail closed without overwriting. + val corruptPayloads = listOf( + "", + "not-json", + "{}", + """{"hasLaunched":"true"}""", + """{"hasLaunched":true,"highestAppVersion":23}""", + """{"hasLaunched":true,"highestAppVersion":"6.6.0!"}""", + """{"hasLaunched":true,"highestBundleVersion":"v1000"}""", + ) + corruptPayloads.forEachIndexed { idx, bad -> + val corruptDir = directory.resolve("corrupt-$idx").apply { mkdirs() } + val corruptFile = corruptDir.resolve(FirstLaunchHistory.FILE_NAME).apply { writeText(bad) } + val corrupted = FirstLaunchHistory(corruptDir, "6.5.0", null, hasPreviousLaunch = false) + check(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion && !corrupted.isFirstLaunchForBundle("1000")) + check(corruptFile.readText() == bad) + } + val file = directory.resolve("file").apply { writeText("") } val failed = FirstLaunchHistory(file, "6.5.0", null, hasPreviousLaunch = false) check(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index fa05d707b..ecfec4667 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -148,6 +148,11 @@ func testFirstLaunchHistory() throws { precondition(!fresh.isFirstLaunchForBundle(nil)) precondition(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) precondition(fresh.isFirstLaunchForBundle(nil)) + // Explicit lookup of another bundle must not overwrite zero-arg startup bundle result. + precondition(!fresh.isFirstLaunchForBundle("999")) + precondition(fresh.isFirstLaunchForBundle(nil)) + // Reject non-numeric version core and traversal strings. + precondition(!fresh.isFirstLaunchForBundle("v1000")) precondition(!fresh.isFirstLaunchForBundle("../escape")) let restart = launch("6.5.0") @@ -155,7 +160,7 @@ func testFirstLaunchHistory() throws { precondition(!restart.isFirstLaunchForBundle("1000")) precondition(!restart.isFirstLaunchForBundle(nil)) precondition(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) - precondition(restart.isFirstLaunchForBundle(nil)) + precondition(!restart.isFirstLaunchForBundle(nil)) let rollback = launch("6.5.0") precondition(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) @@ -187,6 +192,18 @@ func testFirstLaunchHistory() throws { ) precondition(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) + // Corrupted files (empty, invalid JSON, invalid version string) must fail closed without overwriting. + for (idx, bad) in ["", "not-json", "{}", "{\"hasLaunched\":true,\"highestAppVersion\":\"6.6.0!\"}"].enumerated() { + let corruptDir = directory.appendingPathComponent("corrupt-\(idx)") + try FileManager.default.createDirectory(at: corruptDir, withIntermediateDirectories: true) + let corruptFile = corruptDir.appendingPathComponent(FirstLaunchHistory.fileName) + try bad.data(using: .utf8)!.write(to: corruptFile) + let corrupted = FirstLaunchHistory(directory: corruptDir, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + precondition(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion && !corrupted.isFirstLaunchForBundle("1000")) + let remaining = try String(contentsOf: corruptFile, encoding: .utf8) + precondition(remaining == bad) + } + let file = directory.appendingPathComponent("file") try Data().write(to: file) let failed = FirstLaunchHistory(directory: file, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) From 83c0b86e143c1d6f74edb9310c2364ffb3acde3b Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 16:15:09 +0800 Subject: [PATCH 3/7] refactor(device-utils): use 3 independent entries and add resetFirstLaunch --- .../react-native-device-utils/README.md | 17 +- .../DeviceUtilsFirstLaunch.kt | 36 ++- .../FirstLaunchHistory.kt | 286 ++++-------------- .../ReactNativeDeviceUtils.kt | 4 + .../react-native-device-utils/docs/SPEC.md | 33 +- .../ios/DeviceUtilsFirstLaunch.swift | 195 ++++++------ .../ios/ReactNativeDeviceUtils.swift | 4 + .../src/ReactNativeDeviceUtils.nitro.ts | 2 + .../src/__tests__/firstLaunch.test.ts | 97 +++--- .../src/firstLaunch.native.ts | 4 + .../src/firstLaunch.web.ts | 272 ++++++----------- .../tests/InMemoryStoreTest.kt | 25 +- .../tests/main.swift | 30 +- 13 files changed, 385 insertions(+), 620 deletions(-) diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index f57696593..62315b0ba 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -91,6 +91,7 @@ import { isFirstLaunch, isFirstLaunchForCurrentAppVersion, isFirstLaunchForCurrentBundle, + resetFirstLaunch, } from '@onekeyfe/react-native-device-utils/first-launch'; // Call once at app startup. On Web/Desktop/Extension, pass host-sampled @@ -105,6 +106,9 @@ initFirstLaunch({ const firstLaunch = isFirstLaunch(); const firstAppVersionLaunch = isFirstLaunchForCurrentAppVersion(); const firstBundleLaunch = isFirstLaunchForCurrentBundle(); + +// Optional: clear persisted files/keys AND in-memory cache (e.g. on Reset App before JS restart). +resetFirstLaunch(); ``` On iOS and Android, initialize the pure native singleton early in @@ -113,12 +117,12 @@ On iOS and Android, initialize the pure native singleton early in (`DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... })`) so host-specific legacy upgrade detection stays in the app and runs before React Native starts. -Persisted state is a fixed 3-field record (`hasLaunched`, `highestAppVersion`, -`highestBundleVersion`), so storage never grows and requires no cleanup. -Rolling back to a version lower than the recorded highest version returns `false`. -Outside React Native, the record is stored in `localStorage` under -`onekey:device-utils:first-launch`. Call from an extension-owned UI page; an MV3 -service worker returns `false`. +Persisted state is stored as 3 independent plain-text entries (`launched`, +`app_ver`, `bundle_ver` under `1k_first_launch/` on native; `1k_fl_launched`, +`1k_fl_app_ver`, `1k_fl_bundle_ver` in `localStorage` on Web/Desktop/Extension), +so storage never grows and requires no cleanup. Rolling back to a version lower +than the recorded highest version returns `false`. Call from an extension-owned +UI page; an MV3 service worker returns `false`. ## API @@ -130,6 +134,7 @@ service worker returns `false`. | `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. | | `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. | | `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. | +| `resetFirstLaunch()` | `void` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state. | | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise` / `Promise` / `Promise` | iOS, Android | Push-token plumbing; host setup still owns registration. | | `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. | | `getAndClearColdStartLocalNotification()` | `Promise` | iOS, Android | Returns local-notification JSON once; Android returns `""`. | diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt index 0dd8ec9b8..101b34587 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt @@ -15,13 +15,18 @@ object DeviceUtilsFirstLaunch { @Volatile private var history: FirstLaunchHistory? = null + private fun baseDirectory(context: Context): File? { + val appContext = context.applicationContext ?: context + return appContext.noBackupFilesDir ?: appContext.filesDir + } + /** - * Returns true if the persisted first-launch state file already exists on disk. + * Returns true if the persisted launched marker already exists on disk. */ @JvmStatic fun hasPersistedState(context: Context): Boolean { - val filesDir = context.applicationContext?.filesDir ?: context.filesDir ?: return false - return File(filesDir, FirstLaunchHistory.FILE_NAME).exists() + val base = baseDirectory(context) ?: return false + return File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists() } /** @@ -43,7 +48,7 @@ object DeviceUtilsFirstLaunch { /** * Kotlin-friendly initializer whose legacy-detection lambdas are only evaluated - * when no persisted state file exists yet. + * when no persisted launched marker exists yet. */ fun initialize( context: Context, @@ -54,7 +59,7 @@ object DeviceUtilsFirstLaunch { synchronized(lock) { if (history != null) return val appContext = context.applicationContext ?: context - val filesDirectory = appContext.filesDir ?: return + val base = baseDirectory(appContext) ?: return val versionName = try { @Suppress("DEPRECATION") appContext.packageManager.getPackageInfo(appContext.packageName, 0).versionName @@ -63,11 +68,12 @@ object DeviceUtilsFirstLaunch { } catch (_: SecurityException) { null } - val persistedExists = File(filesDirectory, FirstLaunchHistory.FILE_NAME).exists() + val persistedExists = + File(File(base, FirstLaunchHistory.DIRECTORY_NAME), FirstLaunchHistory.LAUNCHED_FILE_NAME).exists() val hasPreviousLaunch = if (persistedExists) false else runCatching(isLegacyInstall).getOrDefault(false) val previousVersion = if (persistedExists) null else runCatching(legacyAppVersion).getOrNull() history = FirstLaunchHistory( - directory = filesDirectory, + baseDirectory = base, appVersion = versionName, previousAppVersion = previousVersion, hasPreviousLaunch = hasPreviousLaunch, @@ -75,6 +81,22 @@ object DeviceUtilsFirstLaunch { } } + /** + * Deletes persisted first-launch files and clears in-memory state so a subsequent + * JS restart within the same native process observes a fresh launch. + */ + @JvmStatic + fun reset(context: Context? = null) { + synchronized(lock) { + if (context != null) { + baseDirectory(context)?.let { base -> + runCatching { File(base, FirstLaunchHistory.DIRECTORY_NAME).deleteRecursively() } + } + } + history = null + } + } + internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean { ensureInitialized(fallbackContext) return history?.isFirstLaunch ?: false diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt index 0a47931e0..4cb214bd9 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -5,84 +5,37 @@ import java.io.FileOutputStream import java.io.IOException internal class FirstLaunchHistory( - directory: File, + baseDirectory: File, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Boolean, ) { - private data class PersistedState( - val hasLaunched: Boolean, - val highestAppVersion: String?, - val highestBundleVersion: String?, - ) - val isFirstLaunch: Boolean val isFirstLaunchForCurrentAppVersion: Boolean - private val directory: File = directory - private val stateFile = File(directory, FILE_NAME) - private var persisted: PersistedState - private val storageAvailable: Boolean + private val storeDirectory = File(baseDirectory, DIRECTORY_NAME) private val bundleResults = mutableMapOf() private var initialBundleVersion: String? = null init { - val validPrevious = validatedVersion(previousAppVersion) + val launchedFile = File(storeDirectory, LAUNCHED_FILE_NAME) + val launchedExists = launchedFile.exists() + isFirstLaunch = if (launchedExists) { + false + } else { + val wrote = writeString(launchedFile, "1") + wrote && !hasPreviousLaunch + } + + val legacyBaseline = if (launchedExists) null else validatedVersion(previousAppVersion) val validCurrent = validatedVersion(appVersion) - val fileExists = stateFile.exists() - val loaded = readState(stateFile) - if (fileExists && loaded == null) { - storageAvailable = false - persisted = PersistedState( - hasLaunched = true, - highestAppVersion = validPrevious, - highestBundleVersion = null, + isFirstLaunchForCurrentAppVersion = if (validCurrent != null) { + evaluateVersionFile( + file = File(storeDirectory, APP_VERSION_FILE_NAME), + currentVersion = validCurrent, + legacyBaseline = legacyBaseline, ) - isFirstLaunch = false - isFirstLaunchForCurrentAppVersion = false } else { - var state = loaded ?: PersistedState( - hasLaunched = false, - highestAppVersion = validPrevious, - highestBundleVersion = null, - ) - var needsWrite = loaded == null - - val computedFirstLaunch = !state.hasLaunched && !hasPreviousLaunch - if (!state.hasLaunched) { - state = state.copy(hasLaunched = true) - needsWrite = true - } - - val computedFirstAppVersion = if (validCurrent != null) { - val baseline = state.highestAppVersion - val isHigher = baseline == null || compareVersions(validCurrent, baseline) > 0 - if (isHigher) { - state = state.copy(highestAppVersion = validCurrent) - needsWrite = true - } - isHigher - } else { - false - } - - if (needsWrite) { - if (writeState(state)) { - storageAvailable = true - persisted = state - isFirstLaunch = computedFirstLaunch - isFirstLaunchForCurrentAppVersion = computedFirstAppVersion - } else { - storageAvailable = false - persisted = state - isFirstLaunch = false - isFirstLaunchForCurrentAppVersion = false - } - } else { - storageAvailable = true - persisted = state - isFirstLaunch = computedFirstLaunch - isFirstLaunchForCurrentAppVersion = computedFirstAppVersion - } + false } } @@ -98,54 +51,59 @@ internal class FirstLaunchHistory( bundleResults[validBundle]?.let { return it } - if (!storageAvailable) { - bundleResults[validBundle] = false - return false - } - val baseline = persisted.highestBundleVersion - val isHigher = baseline == null || compareVersions(validBundle, baseline) > 0 - if (isHigher) { - val next = persisted.copy(highestBundleVersion = validBundle) - if (!writeState(next)) { - bundleResults[validBundle] = false + val result = evaluateVersionFile( + file = File(storeDirectory, BUNDLE_VERSION_FILE_NAME), + currentVersion = validBundle, + legacyBaseline = null, + ) + bundleResults[validBundle] = result + return result + } + + private fun evaluateVersionFile( + file: File, + currentVersion: String, + legacyBaseline: String?, + ): Boolean { + val existing: String? = if (file.exists()) { + val raw = try { + if (!file.isFile) return false + file.readText(Charsets.UTF_8) + } catch (_: IOException) { + return false + } catch (_: SecurityException) { return false } - persisted = next + validatedVersion(raw) ?: return false + } else { + null } - bundleResults[validBundle] = isHigher - return isHigher - } - private fun readState(file: File): PersistedState? = try { - if (!file.isFile) { - null - } else { - parsePersistedJson(file.readText(Charsets.UTF_8)) + val baseline = existing ?: legacyBaseline + val isHigher = baseline == null || compareVersions(currentVersion, baseline) > 0 + if (isHigher) { + return writeString(file, currentVersion) } - } catch (_: IOException) { - null - } catch (_: SecurityException) { - null + if (existing == null) { + writeString(file, baseline) + } + return false } - private fun writeState(state: PersistedState): Boolean { + private fun writeString(target: File, value: String): Boolean { var temp: File? = null return try { - if (!directory.exists() && !directory.mkdirs() && !directory.isDirectory) { + if (!storeDirectory.exists() && !storeDirectory.mkdirs() && !storeDirectory.isDirectory) { false - } else if (!directory.isDirectory) { + } else if (!storeDirectory.isDirectory) { false } else { - val appJson = state.highestAppVersion?.let { "\"$it\"" } ?: "null" - val bundleJson = state.highestBundleVersion?.let { "\"$it\"" } ?: "null" - val json = - """{"hasLaunched":${state.hasLaunched},"highestAppVersion":$appJson,"highestBundleVersion":$bundleJson}""" - temp = File.createTempFile("${stateFile.name}.", ".tmp", directory) + temp = File.createTempFile("${target.name}.", ".tmp", storeDirectory) FileOutputStream(temp).use { fos -> - fos.write(json.toByteArray(Charsets.UTF_8)) + fos.write(value.toByteArray(Charsets.UTF_8)) fos.fd.sync() } - if (temp.renameTo(stateFile)) { + if (temp.renameTo(target)) { temp = null true } else { @@ -161,135 +119,11 @@ internal class FirstLaunchHistory( } } - private fun parsePersistedJson(raw: String): PersistedState? { - var pos = 0 - val len = raw.length - - fun skipWs() { - while (pos < len && raw[pos] in " \t\r\n") pos++ - } - - fun readString(): String? { - if (pos >= len || raw[pos] != '"') return null - pos++ - val sb = StringBuilder() - while (pos < len) { - val c = raw[pos++] - when { - c == '"' -> return sb.toString() - c == '\\' -> { - if (pos >= len) return null - val esc = raw[pos++] - when (esc) { - '"', '\\', '/' -> sb.append(esc) - 'b' -> sb.append('\b') - 'f' -> sb.append('\u000C') - 'n' -> sb.append('\n') - 'r' -> sb.append('\r') - 't' -> sb.append('\t') - 'u' -> { - if (pos + 4 > len) return null - val hex = raw.substring(pos, pos + 4) - val code = hex.toIntOrNull(16) ?: return null - sb.append(code.toChar()) - pos += 4 - } - else -> return null - } - } - c.code < 0x20 -> return null - else -> sb.append(c) - } - } - return null - } - - fun readLiteral(expected: String): Boolean { - if (raw.regionMatches(pos, expected, 0, expected.length)) { - pos += expected.length - return true - } - return false - } - - skipWs() - if (pos >= len || raw[pos] != '{') return null - pos++ - skipWs() - - var hasLaunched: Boolean? = null - var highestAppVersion: String? = null - var highestBundleVersion: String? = null - var sawAppKey = false - var sawBundleKey = false - - if (pos < len && raw[pos] == '}') { - // Missing required hasLaunched field. - return null - } - - while (true) { - skipWs() - val key = readString() ?: return null - skipWs() - if (pos >= len || raw[pos] != ':') return null - pos++ - skipWs() - when (key) { - "hasLaunched" -> { - if (hasLaunched != null) return null - hasLaunched = when { - readLiteral("true") -> true - readLiteral("false") -> false - else -> return null - } - } - "highestAppVersion" -> { - if (sawAppKey) return null - sawAppKey = true - highestAppVersion = if (readLiteral("null")) { - null - } else { - val s = readString() ?: return null - validatedVersion(s) ?: return null - } - } - "highestBundleVersion" -> { - if (sawBundleKey) return null - sawBundleKey = true - highestBundleVersion = if (readLiteral("null")) { - null - } else { - val s = readString() ?: return null - validatedVersion(s) ?: return null - } - } - else -> return null - } - skipWs() - if (pos >= len) return null - when (raw[pos]) { - ',' -> pos++ - '}' -> { - pos++ - break - } - else -> return null - } - } - - skipWs() - if (pos != len) return null - val resolvedHasLaunched = hasLaunched ?: return null - return PersistedState( - hasLaunched = resolvedHasLaunched, - highestAppVersion = highestAppVersion, - highestBundleVersion = highestBundleVersion, - ) - } - companion object { - internal const val FILE_NAME = "onekey-device-utils-first-launch.json" + internal const val DIRECTORY_NAME = "1k_first_launch" + internal const val LAUNCHED_FILE_NAME = "launched" + internal const val APP_VERSION_FILE_NAME = "app_ver" + internal const val BUNDLE_VERSION_FILE_NAME = "bundle_ver" private val VERSION_REGEX = Regex("""^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$""") diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 5e98644f1..cb1633039 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -55,6 +55,10 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven override fun isFirstLaunchForCurrentBundle(bundleVersion: String?): Boolean = DeviceUtilsFirstLaunch.isFirstLaunchForBundle(bundleVersion, NitroModules.applicationContext) + override fun resetFirstLaunch() { + DeviceUtilsFirstLaunch.reset(NitroModules.applicationContext) + } + override fun getInMemoryValue(key: String): InMemoryValue? = InMemoryStore.get(key) override fun setInMemoryValue(key: String, value: InMemoryValue) = InMemoryStore.set(key, value) diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index c3b6ac80d..26acf6ffa 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -15,38 +15,37 @@ Background process starts that run the normal native app bootstrap also count. ## Lifecycle, persistence, and platform behavior -Persisted state is stored as a fixed 3-field JSON object: +Persisted state is stored as **three independent plain-text entries** (no JSON container), so storage size is constant, no cleanup API is needed, and updating one dimension never clobbers or corrupts the others: -```json -{ - "hasLaunched": true, - "highestAppVersion": "6.5.0", - "highestBundleVersion": "1000" -} -``` - -Because only these three fields are persisted, storage size is constant and no cleanup or history pruning API is needed. +| Dimension | Native file (inside `1k_first_launch/`) | Web `localStorage` key | Value | +| --- | --- | --- | --- | +| Installation launched | `launched` | `1k_fl_launched` | `"1"` | +| Highest app version | `app_ver` | `1k_fl_app_ver` | e.g. `"6.5.0"` | +| Highest bundle version | `bundle_ver` | `1k_fl_bundle_ver` | e.g. `"1000"` | -On each launch, the startup path performs a single **read persisted state → compute and freeze current-launch booleans in memory → advance persisted fields if needed** cycle. All getters during that launch return the frozen in-memory booleans and never re-evaluate against the updated disk values. +On each launch, startup reads the persisted entries, computes and freezes the current-launch booleans in memory, and atomically writes any newly established or higher value. All getters during that launch return the frozen in-memory booleans and never re-evaluate against the updated disk values. | Platform | Initialization | Storage | Legacy-install evidence | | --- | --- | --- | --- | -| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in Application Support | Owned by the host app. Use `hasPersistedState()` (or `hasPersistedStateNumber` returning `NSNumber` for `perform(_:)`) to skip legacy checks once persisted state exists. | -| Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `onekey-device-utils-first-launch.json` in `context.filesDir` | Owned by the host app (lambdas are only invoked when no persisted file exists yet). | -| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` once at UI startup before reading getters. | `localStorage` key `onekey:device-utils:first-launch` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | +| iOS | Host calls `DeviceUtilsFirstLaunch.initialize(options:)` (or dynamically via `NSClassFromString("OneKeyDeviceUtilsFirstLaunch")` + `initializeWithOptions:`) in `AppDelegate.didFinishLaunchingWithOptions` before initializing app storage. Lazy fallback initializes with `isLegacyInstall = false`. | `Library/Application Support/1k_first_launch/` (`isExcludedFromBackup = true`) | Owned by the host app. Use `hasPersistedState()` (or `hasPersistedStateNumber` returning `NSNumber` for `perform(_:)`) to skip legacy checks once `launched` exists. | +| Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `context.noBackupFilesDir/1k_first_launch/` (immune to Clear Cache and Auto Backup) | Owned by the host app (lambdas are only invoked when `launched` does not exist yet). | +| Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` once at UI startup before reading getters. | `localStorage` keys `1k_fl_launched`, `1k_fl_app_ver`, `1k_fl_bundle_ver` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | + +`resetFirstLaunch()` (and native `DeviceUtilsFirstLaunch.reset()`) removes the `1k_first_launch/` directory (or the 3 `localStorage` keys) **and clears the in-memory launch cache**, so a Reset App flow followed by a JS soft restart in the same native process observes a fresh launch. -Version strings must have a numeric dot-separated core with optional SemVer pre-release (`-...`) and build metadata (`+...`) suffixes (1–120 ASCII chars, e.g. `6.5.0`, `6.5.0-beta.1`, `1000`). Non-numeric cores such as `v6.5.0` are rejected. Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted field. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. +Version strings must have a numeric dot-separated core with optional SemVer pre-release (`-...`) and build metadata (`+...`) suffixes (1–120 ASCII chars, e.g. `6.5.0`, `6.5.0-beta.1`, `1000`). Non-numeric cores such as `v6.5.0` are rejected. Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted entry. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. -Missing startup initialization, unavailable or corrupted storage (malformed JSON, wrong field types, or invalid stored version strings), invalid identifiers, and write failures fail closed and return `false` without overwriting the damaged record. Zero-argument getters remain bound to the startup identities and are unaffected by later explicit version lookups. On Web/Desktop/Extension, `initFirstLaunch(...)` commits the startup snapshot in a single synchronous `localStorage.setItem`; getters called before `initFirstLaunch(...)` return `false` without touching storage. Because synchronous Web Storage has no cross-document lock, simultaneous first loads across two separate tabs may both observe an absent key. +Missing startup initialization, unavailable or corrupted entries (empty or invalid stored version strings), invalid identifiers, and write failures fail closed for the affected entry and return `false` without overwriting the damaged entry. Zero-argument getters remain bound to the startup identities and are unaffected by later explicit version lookups. On Web/Desktop/Extension, getters called before `initFirstLaunch(...)` return `false` without touching storage. Because synchronous Web Storage has no cross-document lock, simultaneous first loads across two separate tabs may both observe an absent key. ## Web, desktop renderer, and extension pages The `@onekeyfe/react-native-device-utils/first-launch` entry point exposes: -- `initFirstLaunch(options?: { appVersion?: string; bundleVersion?: string }): void` +- `initFirstLaunch(options?: { appVersion?: string; bundleVersion?: string; isLegacyInstall?: boolean; legacyAppVersion?: string }): void` - `isFirstLaunch(): boolean` - `isFirstLaunchForCurrentAppVersion(appVersion?: string): boolean` - `isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean` +- `resetFirstLaunch(): void` React Native delegates to `ReactNativeDeviceUtils`. Web documents, Electron renderers, and extension-owned pages share `src/firstLaunch.web.ts` backed by `window.localStorage`. After `initFirstLaunch(...)` runs at startup, getters can be called with zero arguments to read the cached launch results. Server runtimes and MV3 service workers have no `window.localStorage` and return `false`. diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index 539589725..c76886782 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -5,11 +5,13 @@ public final class DeviceUtilsFirstLaunch: NSObject { private static let lock = NSLock() private static var history: FirstLaunchHistory? - /// Returns true if the persisted first-launch state file already exists on disk. + /// Returns true if the persisted launched marker already exists on disk. public static func hasPersistedState() -> Bool { guard let directory = defaultDirectory() else { return false } - let fileURL = directory.appendingPathComponent(FirstLaunchHistory.fileName) - return FileManager.default.fileExists(atPath: fileURL.path) + let launchedURL = directory + .appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + .appendingPathComponent(FirstLaunchHistory.launchedFileName) + return FileManager.default.fileExists(atPath: launchedURL.path) } /// Object-returning variant of `hasPersistedState()` safe for dynamic invocation @@ -42,13 +44,25 @@ public final class DeviceUtilsFirstLaunch: NSObject { guard history == nil else { return } guard let directory = defaultDirectory() else { return } history = FirstLaunchHistory( - directory: directory, + baseDirectory: directory, appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, previousAppVersion: legacyAppVersion, hasPreviousLaunch: isLegacyInstall ) } + /// Deletes persisted first-launch files and clears in-memory state so a subsequent + /// JS restart within the same native process observes a fresh launch. + @objc public static func reset() { + lock.lock() + defer { lock.unlock() } + if let directory = defaultDirectory() { + let storeDir = directory.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + try? FileManager.default.removeItem(at: storeDir) + } + history = nil + } + static var value: Bool { withHistory(default: false) { $0.isFirstLaunch } } @@ -75,7 +89,7 @@ public final class DeviceUtilsFirstLaunch: NSObject { return fallback } let created = FirstLaunchHistory( - directory: directory, + baseDirectory: directory, appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, previousAppVersion: nil, hasPreviousLaunch: false @@ -86,79 +100,40 @@ public final class DeviceUtilsFirstLaunch: NSObject { } final class FirstLaunchHistory { - static let fileName = "onekey-device-utils-first-launch.json" - - private struct PersistedState: Codable { - var hasLaunched: Bool - var highestAppVersion: String? - var highestBundleVersion: String? - } + static let directoryName = "1k_first_launch" + static let launchedFileName = "launched" + static let appVersionFileName = "app_ver" + static let bundleVersionFileName = "bundle_ver" let isFirstLaunch: Bool let isFirstLaunchForCurrentAppVersion: Bool - private let fileURL: URL - private var persisted: PersistedState - private var storageAvailable: Bool + private let storeDirectory: URL private var bundleResults: [String: Bool] = [:] private var initialBundleVersion: String? - init(directory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { - fileURL = directory.appendingPathComponent(Self.fileName) - let validPrevious = Self.validatedVersion(previousAppVersion) - let validCurrent = Self.validatedVersion(appVersion) + init(baseDirectory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { + let dir = baseDirectory.appendingPathComponent(Self.directoryName, isDirectory: true) + storeDirectory = dir - let fileExists = FileManager.default.fileExists(atPath: fileURL.path) - let loaded = Self.readState(from: fileURL) - if fileExists && loaded == nil { - storageAvailable = false - persisted = PersistedState(hasLaunched: true, highestAppVersion: validPrevious, highestBundleVersion: nil) + let launchedURL = dir.appendingPathComponent(Self.launchedFileName) + let launchedExists = FileManager.default.fileExists(atPath: launchedURL.path) + if launchedExists { isFirstLaunch = false - isFirstLaunchForCurrentAppVersion = false - return - } - var state = loaded ?? PersistedState( - hasLaunched: false, - highestAppVersion: validPrevious, - highestBundleVersion: nil - ) - var needsWrite = loaded == nil - - let computedFirstLaunch = !state.hasLaunched && !hasPreviousLaunch - if !state.hasLaunched { - state.hasLaunched = true - needsWrite = true - } - - let computedFirstAppVersion: Bool - if let validCurrent { - let baseline = state.highestAppVersion - let isHigher = baseline == nil || Self.compareVersions(validCurrent, baseline!) > 0 - computedFirstAppVersion = isHigher - if isHigher { - state.highestAppVersion = validCurrent - needsWrite = true - } } else { - computedFirstAppVersion = false + let wrote = Self.writeString("1", to: launchedURL, directory: dir) + isFirstLaunch = wrote && !hasPreviousLaunch } - if needsWrite { - if Self.writeState(state, to: fileURL, directory: directory) { - storageAvailable = true - persisted = state - isFirstLaunch = computedFirstLaunch - isFirstLaunchForCurrentAppVersion = computedFirstAppVersion - } else { - storageAvailable = false - persisted = state - isFirstLaunch = false - isFirstLaunchForCurrentAppVersion = false - } + let legacyBaseline = launchedExists ? nil : Self.validatedVersion(previousAppVersion) + if let validCurrent = Self.validatedVersion(appVersion) { + isFirstLaunchForCurrentAppVersion = Self.evaluateVersionFile( + at: dir.appendingPathComponent(Self.appVersionFileName), + directory: dir, + currentVersion: validCurrent, + legacyBaseline: legacyBaseline + ) } else { - storageAvailable = true - persisted = state - isFirstLaunch = computedFirstLaunch - isFirstLaunchForCurrentAppVersion = computedFirstAppVersion + isFirstLaunchForCurrentAppVersion = false } } @@ -175,23 +150,58 @@ final class FirstLaunchHistory { if let cached = bundleResults[validBundle] { return cached } - guard storageAvailable else { - bundleResults[validBundle] = false - return false - } - let baseline = persisted.highestBundleVersion - let isHigher = baseline == nil || Self.compareVersions(validBundle, baseline!) > 0 - if isHigher { - var next = persisted - next.highestBundleVersion = validBundle - guard Self.writeState(next, to: fileURL, directory: fileURL.deletingLastPathComponent()) else { - bundleResults[validBundle] = false + let result = Self.evaluateVersionFile( + at: storeDirectory.appendingPathComponent(Self.bundleVersionFileName), + directory: storeDirectory, + currentVersion: validBundle, + legacyBaseline: nil + ) + bundleResults[validBundle] = result + return result + } + + private static func evaluateVersionFile( + at fileURL: URL, + directory: URL, + currentVersion: String, + legacyBaseline: String? + ) -> Bool { + let exists = FileManager.default.fileExists(atPath: fileURL.path) + let existing: String? + if exists { + guard let raw = try? String(contentsOf: fileURL, encoding: .utf8), + let valid = validatedVersion(raw) else { + // Corrupted file: fail closed without overwriting. return false } - persisted = next + existing = valid + } else { + existing = nil + } + + let baseline = existing ?? legacyBaseline + let isHigher = baseline == nil || compareVersions(currentVersion, baseline!) > 0 + if isHigher { + return writeString(currentVersion, to: fileURL, directory: directory) + } + if existing == nil, let baseline { + _ = writeString(baseline, to: fileURL, directory: directory) + } + return false + } + + private static func writeString(_ value: String, to url: URL, directory: URL) -> Bool { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var dirURL = directory + var values = URLResourceValues() + values.isExcludedFromBackup = true + try? dirURL.setResourceValues(values) + try Data(value.utf8).write(to: url, options: .atomic) + return true + } catch { + return false } - bundleResults[validBundle] = isHigher - return isHigher } static func compareVersions(_ a: String, _ b: String) -> Int { @@ -280,29 +290,4 @@ final class FirstLaunchHistory { let pattern = "^[0-9]+(?:\\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$" return try! NSRegularExpression(pattern: pattern, options: []) }() - - private static func readState(from url: URL) -> PersistedState? { - guard let data = try? Data(contentsOf: url), - let decoded = try? JSONDecoder().decode(PersistedState.self, from: data) else { - return nil - } - if let app = decoded.highestAppVersion, validatedVersion(app) == nil { - return nil - } - if let bundle = decoded.highestBundleVersion, validatedVersion(bundle) == nil { - return nil - } - return decoded - } - - private static func writeState(_ state: PersistedState, to url: URL, directory: URL) -> Bool { - do { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let data = try JSONEncoder().encode(state) - try data.write(to: url, options: .atomic) - return true - } catch { - return false - } - } } diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 243c3be9c..00c70a8dc 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -86,6 +86,10 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { DeviceUtilsFirstLaunch.forBundle(bundleVersion) } + func resetFirstLaunch() throws { + DeviceUtilsFirstLaunch.reset() + } + override init() { super.init() restoreUserInterfaceStyle() diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 619eefa60..a95a4927e 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -135,6 +135,8 @@ export interface ReactNativeDeviceUtils isFirstLaunchForCurrentAppVersion(): boolean; /** First launch of a bundle version higher than any previously launched bundle. */ isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean; + /** Clears persisted first-launch files and in-memory state (e.g. on Reset App). */ + resetFirstLaunch(): void; // Process-owned primitive Map, shared by all runtimes and never persisted. getInMemoryValue(key: string): InMemoryValue | undefined; setInMemoryValue(key: string, value: InMemoryValue): void; diff --git a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts index 106acddb3..a7f02fe21 100644 --- a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts +++ b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts @@ -46,12 +46,14 @@ afterEach(() => { } }); -it('records installation, highest app version, and highest bundle version in a single write', () => { +it('records installation, highest app version, and highest bundle version as 3 independent keys', () => { const storage = createStorage(); const startup = openDocument(storage); startup.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); - expect(storage.setItem).toHaveBeenCalledTimes(1); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_launched', '1'); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_app_ver', '6.5.0'); + expect(storage.setItem).toHaveBeenCalledWith('1k_fl_bundle_ver', '1000'); expect(startup.isFirstLaunch()).toBe(true); expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(true); expect(startup.isFirstLaunchForCurrentBundle()).toBe(true); @@ -59,7 +61,6 @@ it('records installation, highest app version, and highest bundle version in a s expect(startup.isFirstLaunch()).toBe(true); expect(startup.isFirstLaunchForCurrentAppVersion('6.5.0')).toBe(true); expect(startup.isFirstLaunchForCurrentBundle('1000')).toBe(true); - expect(storage.setItem).toHaveBeenCalledTimes(1); // Explicit lookup of another identity must not overwrite startup zero-arg results or evict startup cache. expect(startup.isFirstLaunchForCurrentAppVersion('6.6.0')).toBe(true); @@ -81,9 +82,8 @@ it('records installation, highest app version, and highest bundle version in a s expect(ota.isFirstLaunch()).toBe(false); expect(ota.isFirstLaunchForCurrentAppVersion()).toBe(false); expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); - expect(ota.isFirstLaunchForCurrentBundle()).toBe(true); - // Rollback to lower bundle returns false and preserves highestBundleVersion + // Rollback to lower bundle returns false and preserves highest bundle version const rollback = openDocument(storage); rollback.initFirstLaunch({ appVersion: '6.6.0', bundleVersion: '1000' }); expect(rollback.isFirstLaunch()).toBe(false); @@ -105,6 +105,29 @@ it('records installation, highest app version, and highest bundle version in a s expect(downgrade.isFirstLaunchForCurrentBundle()).toBe(false); }); +it('clears both persisted keys and in-memory state on resetFirstLaunch', () => { + const storage = createStorage(); + const doc = openDocument(storage); + + doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(doc.isFirstLaunch()).toBe(true); + + // Simulate normal restart -> false + const restarted = openDocument(storage); + restarted.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(restarted.isFirstLaunch()).toBe(false); + expect(restarted.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(restarted.isFirstLaunchForCurrentBundle()).toBe(false); + + // Reset in the same runtime (e.g. Reset App + JS soft restart) + restarted.resetFirstLaunch(); + expect(restarted.isFirstLaunch()).toBe(false); + restarted.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); + expect(restarted.isFirstLaunch()).toBe(true); + expect(restarted.isFirstLaunchForCurrentAppVersion()).toBe(true); + expect(restarted.isFirstLaunchForCurrentBundle()).toBe(true); +}); + it('does not touch storage before initFirstLaunch so legacy init is never consumed early', () => { const storage = createStorage(); const doc = openDocument(storage); @@ -126,52 +149,22 @@ it('does not touch storage before initFirstLaunch so legacy init is never consum expect(doc.isFirstLaunchForCurrentBundle()).toBe(true); }); -it('honors host-provided legacy upgrade flags without guessing from unrelated keys', () => { - const thirdPartyStorage = createStorage({ 'third-party-sdk': '1' }); - const freshWithNoise = openDocument(thirdPartyStorage); - freshWithNoise.initFirstLaunch({ - appVersion: '6.5.0', - bundleVersion: '1000', - }); - expect(freshWithNoise.isFirstLaunch()).toBe(true); - - const legacyUpgradeStorage = createStorage(); - const upgradedHigher = openDocument(legacyUpgradeStorage); - upgradedHigher.initFirstLaunch({ - appVersion: '6.6.0', - bundleVersion: '1001', - isLegacyInstall: true, - legacyAppVersion: '6.5.0', +it('isolates corrupted keys without overwriting them or breaking healthy keys', () => { + const storage = createStorage({ + '1k_fl_launched': '1', + '1k_fl_app_ver': '6.6.0!', + '1k_fl_bundle_ver': '1000', }); - expect(upgradedHigher.isFirstLaunch()).toBe(false); - expect(upgradedHigher.isFirstLaunchForCurrentAppVersion()).toBe(true); - expect(upgradedHigher.isFirstLaunchForCurrentBundle()).toBe(true); -}); + const doc = openDocument(storage); + doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1001' }); -it('fails closed and preserves storage when persisted history is corrupted', () => { - const corruptPayloads = [ - '', - 'not-json', - 'null', - '{}', - '[]', - JSON.stringify({ hasLaunched: 'yes' }), - JSON.stringify({ hasLaunched: true, highestAppVersion: 23 }), - JSON.stringify({ hasLaunched: true, highestAppVersion: '6.6.0!' }), - JSON.stringify({ hasLaunched: true, highestBundleVersion: 'v1000' }), - ]; - - for (const payload of corruptPayloads) { - const storage = createStorage({ - 'onekey:device-utils:first-launch': payload, - }); - const doc = openDocument(storage); - doc.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); - expect(doc.isFirstLaunch()).toBe(false); - expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); - expect(doc.isFirstLaunchForCurrentBundle()).toBe(false); - expect(storage.setItem).not.toHaveBeenCalled(); - } + expect(doc.isFirstLaunch()).toBe(false); + // Corrupted app_ver fails closed and is NOT overwritten + expect(doc.isFirstLaunchForCurrentAppVersion()).toBe(false); + expect(storage.getItem('1k_fl_app_ver')).toBe('6.6.0!'); + // Healthy bundle_ver still works independently + expect(doc.isFirstLaunchForCurrentBundle()).toBe(true); + expect(storage.getItem('1k_fl_bundle_ver')).toBe('1001'); }); it('validates numeric version core and handles prerelease comparisons accurately', () => { @@ -193,7 +186,7 @@ it('validates numeric version core and handles prerelease comparisons accurately expect(doc.compareVersions('1000', '999')).toBeGreaterThan(0); }); -it('returns false without browser storage and fails closed on write errors', () => { +it('returns false without browser storage and tolerates blocked writes', () => { const server = openDocument(); server.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); expect(server.isFirstLaunch()).toBe(false); @@ -212,9 +205,8 @@ it('returns false without browser storage and fails closed on write errors', () blocked.initFirstLaunch({ appVersion: '2.0', bundleVersion: '1000' }); expect(blocked.isFirstLaunch()).toBe(false); - // If the single startup commit throws, all three startup flags must be false. const storage = createStorage(); - storage.setItem.mockImplementationOnce(() => { + storage.setItem.mockImplementation(() => { throw new Error('Storage is full'); }); const startup = openDocument(storage); @@ -222,5 +214,4 @@ it('returns false without browser storage and fails closed on write errors', () expect(startup.isFirstLaunch()).toBe(false); expect(startup.isFirstLaunchForCurrentAppVersion()).toBe(false); expect(startup.isFirstLaunchForCurrentBundle()).toBe(false); - expect(storage.setItem).toHaveBeenCalledTimes(1); }); diff --git a/native-modules/react-native-device-utils/src/firstLaunch.native.ts b/native-modules/react-native-device-utils/src/firstLaunch.native.ts index 8bc20b926..e1a364571 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.native.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.native.ts @@ -38,3 +38,7 @@ export function isFirstLaunchForCurrentBundle( ): boolean { return ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(bundleVersion); } + +export function resetFirstLaunch(): void { + ReactNativeDeviceUtils.resetFirstLaunch(); +} diff --git a/native-modules/react-native-device-utils/src/firstLaunch.web.ts b/native-modules/react-native-device-utils/src/firstLaunch.web.ts index 21bdfe808..bb255a88b 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.web.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.web.ts @@ -14,19 +14,17 @@ export interface FirstLaunchInitOptions { legacyAppVersion?: string; } -interface PersistedFirstLaunchState { - hasLaunched: boolean; - highestAppVersion: string | null; - highestBundleVersion: string | null; -} +export const FIRST_LAUNCH_KEYS = { + launched: '1k_fl_launched', + appVersion: '1k_fl_app_ver', + bundleVersion: '1k_fl_bundle_ver', +} as const; -export const FIRST_LAUNCH_STORAGE_KEY = 'onekey:device-utils:first-launch'; const validVersionPattern = /^[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; const digitsOnly = /^[0-9]+$/; let initialized = false; -let storageAvailable = false; let cachedFirstLaunch = false; let startupAppVersion: string | undefined; let startupBundleVersion: string | undefined; @@ -135,79 +133,49 @@ function getStorage(): Storage | null { } } -function parseOptionalVersionField( - value: unknown -): { ok: true; value: string | null } | { ok: false } { - if (value === undefined || value === null) { - return { ok: true, value: null }; - } - if (isValidVersion(value)) { - return { ok: true, value }; +function safeGet(storage: Storage, key: string): { ok: true; value: string | null } | { ok: false } { + try { + return { ok: true, value: storage.getItem(key) }; + } catch { + return { ok: false }; } - return { ok: false }; } -function readState( - storage: Storage, - legacyAppVersion?: string -): { - state: PersistedFirstLaunchState; - existed: boolean; -} | null { +function safeSet(storage: Storage, key: string, value: string): boolean { try { - const raw = storage.getItem(FIRST_LAUNCH_STORAGE_KEY); - if (raw === null) { - return { - state: { - hasLaunched: false, - highestAppVersion: isValidVersion(legacyAppVersion) - ? legacyAppVersion - : null, - highestBundleVersion: null, - }, - existed: false, - }; - } - const parsed: unknown = JSON.parse(raw); - if ( - typeof parsed !== 'object' || - parsed === null || - Array.isArray(parsed) - ) { - return null; - } - const record = parsed as Record; - if (typeof record.hasLaunched !== 'boolean') { - return null; - } - const appField = parseOptionalVersionField(record.highestAppVersion); - const bundleField = parseOptionalVersionField(record.highestBundleVersion); - if (!appField.ok || !bundleField.ok) { - return null; - } - return { - state: { - hasLaunched: record.hasLaunched, - highestAppVersion: appField.value, - highestBundleVersion: bundleField.value, - }, - existed: true, - }; + storage.setItem(key, value); + return true; } catch { - return null; + return false; } } -function writeState( +function evaluateVersionKey( storage: Storage, - state: PersistedFirstLaunchState + key: string, + currentVersion: string, + legacyBaseline?: string ): boolean { - try { - storage.setItem(FIRST_LAUNCH_STORAGE_KEY, JSON.stringify(state)); - return true; - } catch { + const existing = safeGet(storage, key); + if (!existing.ok) { + return false; + } + if (existing.value !== null && !isValidVersion(existing.value)) { + // Corrupted stored value: fail closed without overwriting. return false; } + const baseline = + existing.value ?? (isValidVersion(legacyBaseline) ? legacyBaseline : null); + const isHigher = + baseline === null || compareVersions(currentVersion, baseline) > 0; + if (isHigher) { + return safeSet(storage, key, currentVersion); + } + if (existing.value === null && baseline !== null) { + // Persist the legacy baseline so future launches don't need legacy input. + safeSet(storage, key, baseline); + } + return false; } export function initFirstLaunch(options?: FirstLaunchInitOptions): void { @@ -225,8 +193,8 @@ export function initFirstLaunch(options?: FirstLaunchInitOptions): void { startupAppVersion = validAppVersion; startupBundleVersion = validBundleVersion; - const failClosed = () => { - storageAvailable = false; + const storage = getStorage(); + if (!storage) { cachedFirstLaunch = false; if (validAppVersion !== undefined) { cachedAppResults.set(validAppVersion, false); @@ -234,65 +202,46 @@ export function initFirstLaunch(options?: FirstLaunchInitOptions): void { if (validBundleVersion !== undefined) { cachedBundleResults.set(validBundleVersion, false); } - }; - - const storage = getStorage(); - if (!storage) { - failClosed(); return; } const isLegacyInstall = options?.isLegacyInstall === true; - const loaded = readState(storage, options?.legacyAppVersion); - if (!loaded) { - failClosed(); - return; - } - - const { state, existed } = loaded; - const nextState: PersistedFirstLaunchState = { ...state }; - let needsWrite = !existed; - - const computedFirstLaunch = !state.hasLaunched && !isLegacyInstall; - if (!state.hasLaunched) { - nextState.hasLaunched = true; - needsWrite = true; - } - - let computedAppVersion = false; - if (validAppVersion !== undefined) { - computedAppVersion = - nextState.highestAppVersion === null || - compareVersions(validAppVersion, nextState.highestAppVersion) > 0; - if (computedAppVersion) { - nextState.highestAppVersion = validAppVersion; - needsWrite = true; - } - } + const launchedRead = safeGet(storage, FIRST_LAUNCH_KEYS.launched); + const isFreshStorage = launchedRead.ok && launchedRead.value === null; - let computedBundleVersion = false; - if (validBundleVersion !== undefined) { - computedBundleVersion = - nextState.highestBundleVersion === null || - compareVersions(validBundleVersion, nextState.highestBundleVersion) > 0; - if (computedBundleVersion) { - nextState.highestBundleVersion = validBundleVersion; - needsWrite = true; - } + if (!launchedRead.ok) { + cachedFirstLaunch = false; + } else if (launchedRead.value === null) { + const wrote = safeSet(storage, FIRST_LAUNCH_KEYS.launched, '1'); + cachedFirstLaunch = wrote && !isLegacyInstall; + } else { + // Present ("1" or corrupted): not a first launch, do not overwrite. + cachedFirstLaunch = false; } - if (needsWrite && !writeState(storage, nextState)) { - failClosed(); - return; - } + const legacyBaseline = isFreshStorage ? options?.legacyAppVersion : undefined; - storageAvailable = true; - cachedFirstLaunch = computedFirstLaunch; if (validAppVersion !== undefined) { - cachedAppResults.set(validAppVersion, computedAppVersion); + cachedAppResults.set( + validAppVersion, + evaluateVersionKey( + storage, + FIRST_LAUNCH_KEYS.appVersion, + validAppVersion, + legacyBaseline + ) + ); } + if (validBundleVersion !== undefined) { - cachedBundleResults.set(validBundleVersion, computedBundleVersion); + cachedBundleResults.set( + validBundleVersion, + evaluateVersionKey( + storage, + FIRST_LAUNCH_KEYS.bundleVersion, + validBundleVersion + ) + ); } } @@ -321,38 +270,12 @@ export function isFirstLaunchForCurrentAppVersion( if (cached !== undefined) { return cached; } - if (!storageAvailable) { - cachedAppResults.set(appVersion, false); - return false; - } const storage = getStorage(); - if (!storage) { - cachedAppResults.set(appVersion, false); - return false; - } - const loaded = readState(storage); - if (!loaded) { - storageAvailable = false; - cachedAppResults.set(appVersion, false); - return false; - } - const { state } = loaded; - const isHigher = - state.highestAppVersion === null || - compareVersions(appVersion, state.highestAppVersion) > 0; - if (isHigher) { - const nextState: PersistedFirstLaunchState = { - ...state, - hasLaunched: true, - highestAppVersion: appVersion, - }; - if (!writeState(storage, nextState)) { - cachedAppResults.set(appVersion, false); - return false; - } - } - cachedAppResults.set(appVersion, isHigher); - return isHigher; + const result = storage + ? evaluateVersionKey(storage, FIRST_LAUNCH_KEYS.appVersion, appVersion) + : false; + cachedAppResults.set(appVersion, result); + return result; } export function isFirstLaunchForCurrentBundle( @@ -373,36 +296,29 @@ export function isFirstLaunchForCurrentBundle( if (cached !== undefined) { return cached; } - if (!storageAvailable) { - cachedBundleResults.set(bundleVersion, false); - return false; - } const storage = getStorage(); - if (!storage) { - cachedBundleResults.set(bundleVersion, false); - return false; - } - const loaded = readState(storage); - if (!loaded) { - storageAvailable = false; - cachedBundleResults.set(bundleVersion, false); - return false; - } - const { state } = loaded; - const isHigher = - state.highestBundleVersion === null || - compareVersions(bundleVersion, state.highestBundleVersion) > 0; - if (isHigher) { - const nextState: PersistedFirstLaunchState = { - ...state, - hasLaunched: true, - highestBundleVersion: bundleVersion, - }; - if (!writeState(storage, nextState)) { - cachedBundleResults.set(bundleVersion, false); - return false; + const result = storage + ? evaluateVersionKey(storage, FIRST_LAUNCH_KEYS.bundleVersion, bundleVersion) + : false; + cachedBundleResults.set(bundleVersion, result); + return result; +} + +export function resetFirstLaunch(): void { + const storage = getStorage(); + if (storage) { + try { + storage.removeItem(FIRST_LAUNCH_KEYS.launched); + storage.removeItem(FIRST_LAUNCH_KEYS.appVersion); + storage.removeItem(FIRST_LAUNCH_KEYS.bundleVersion); + } catch { + // Ignore storage errors during reset. } } - cachedBundleResults.set(bundleVersion, isHigher); - return isHigher; + initialized = false; + cachedFirstLaunch = false; + startupAppVersion = undefined; + startupBundleVersion = undefined; + cachedAppResults.clear(); + cachedBundleResults.clear(); } diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 75b4f3c6e..463a5a498 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -184,22 +184,17 @@ fun main() { val legacyUpgraded = FirstLaunchHistory(directory.resolve("legacy-upgraded"), "6.6.0", "6.5.0", hasPreviousLaunch = true) check(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) - // Corrupted files (empty, invalid JSON, wrong types, invalid version string) must fail closed without overwriting. - val corruptPayloads = listOf( - "", - "not-json", - "{}", - """{"hasLaunched":"true"}""", - """{"hasLaunched":true,"highestAppVersion":23}""", - """{"hasLaunched":true,"highestAppVersion":"6.6.0!"}""", - """{"hasLaunched":true,"highestBundleVersion":"v1000"}""", - ) + // Corrupted individual files must fail closed without overwriting or breaking healthy files. + val corruptPayloads = listOf("", "6.6.0!", "v1000") corruptPayloads.forEachIndexed { idx, bad -> - val corruptDir = directory.resolve("corrupt-$idx").apply { mkdirs() } - val corruptFile = corruptDir.resolve(FirstLaunchHistory.FILE_NAME).apply { writeText(bad) } - val corrupted = FirstLaunchHistory(corruptDir, "6.5.0", null, hasPreviousLaunch = false) - check(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion && !corrupted.isFirstLaunchForBundle("1000")) - check(corruptFile.readText() == bad) + val corruptBase = directory.resolve("corrupt-$idx") + val corruptStore = corruptBase.resolve(FirstLaunchHistory.DIRECTORY_NAME).apply { mkdirs() } + corruptStore.resolve(FirstLaunchHistory.LAUNCHED_FILE_NAME).writeText("1") + val badAppFile = corruptStore.resolve(FirstLaunchHistory.APP_VERSION_FILE_NAME).apply { writeText(bad) } + val corrupted = FirstLaunchHistory(corruptBase, "6.5.0", null, hasPreviousLaunch = false) + check(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion) + check(badAppFile.readText() == bad) + check(corrupted.isFirstLaunchForBundle("1000")) } val file = directory.resolve("file").apply { writeText("") } diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index ecfec4667..485bfd5b3 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -136,7 +136,7 @@ func testFirstLaunchHistory() throws { func launch(_ version: String, previous: String? = nil) -> FirstLaunchHistory { FirstLaunchHistory( - directory: directory, + baseDirectory: directory, appVersion: version, previousAppVersion: previous, hasPreviousLaunch: previous != nil @@ -177,7 +177,7 @@ func testFirstLaunchHistory() throws { precondition(!downgrade.isFirstLaunchForBundle("1001")) let legacySameVersion = FirstLaunchHistory( - directory: directory.appendingPathComponent("legacy-same"), + baseDirectory: directory.appendingPathComponent("legacy-same"), appVersion: "6.5.0", previousAppVersion: "6.5.0", hasPreviousLaunch: true @@ -185,28 +185,32 @@ func testFirstLaunchHistory() throws { precondition(!legacySameVersion.isFirstLaunch && !legacySameVersion.isFirstLaunchForCurrentAppVersion) let legacyUpgraded = FirstLaunchHistory( - directory: directory.appendingPathComponent("legacy-upgraded"), + baseDirectory: directory.appendingPathComponent("legacy-upgraded"), appVersion: "6.6.0", previousAppVersion: "6.5.0", hasPreviousLaunch: true ) precondition(!legacyUpgraded.isFirstLaunch && legacyUpgraded.isFirstLaunchForCurrentAppVersion) - // Corrupted files (empty, invalid JSON, invalid version string) must fail closed without overwriting. - for (idx, bad) in ["", "not-json", "{}", "{\"hasLaunched\":true,\"highestAppVersion\":\"6.6.0!\"}"].enumerated() { - let corruptDir = directory.appendingPathComponent("corrupt-\(idx)") - try FileManager.default.createDirectory(at: corruptDir, withIntermediateDirectories: true) - let corruptFile = corruptDir.appendingPathComponent(FirstLaunchHistory.fileName) - try bad.data(using: .utf8)!.write(to: corruptFile) - let corrupted = FirstLaunchHistory(directory: corruptDir, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) - precondition(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion && !corrupted.isFirstLaunchForBundle("1000")) - let remaining = try String(contentsOf: corruptFile, encoding: .utf8) + // Corrupted individual files must fail closed without overwriting or breaking healthy files. + for (idx, bad) in ["", "6.6.0!", "v1000"].enumerated() { + let corruptBase = directory.appendingPathComponent("corrupt-\(idx)") + let corruptStore = corruptBase.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + try FileManager.default.createDirectory(at: corruptStore, withIntermediateDirectories: true) + try Data("1".utf8).write(to: corruptStore.appendingPathComponent(FirstLaunchHistory.launchedFileName)) + let badAppFile = corruptStore.appendingPathComponent(FirstLaunchHistory.appVersionFileName) + try Data(bad.utf8).write(to: badAppFile) + let corrupted = FirstLaunchHistory(baseDirectory: corruptBase, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + precondition(!corrupted.isFirstLaunch && !corrupted.isFirstLaunchForCurrentAppVersion) + let remaining = try String(contentsOf: badAppFile, encoding: .utf8) precondition(remaining == bad) + // Healthy bundle file still works independently. + precondition(corrupted.isFirstLaunchForBundle("1000")) } let file = directory.appendingPathComponent("file") try Data().write(to: file) - let failed = FirstLaunchHistory(directory: file, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) + let failed = FirstLaunchHistory(baseDirectory: file, appVersion: "6.5.0", previousAppVersion: nil, hasPreviousLaunch: false) precondition(!failed.isFirstLaunch && !failed.isFirstLaunchForCurrentAppVersion && !failed.isFirstLaunchForBundle("1000")) } From 0699f99039d1e4edf1fd4ef85ab7dbdb3f318ea4 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 16:22:20 +0800 Subject: [PATCH 4/7] fix(device-utils): bind reloaded JS bundle and reject trailing newlines on iOS --- .../ios/DeviceUtilsFirstLaunch.swift | 5 +++-- .../src/firstLaunch.native.ts | 10 +++++++++- .../tests/InMemoryStoreTest.kt | 3 ++- .../react-native-device-utils/tests/main.swift | 3 ++- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index c76886782..570e968ac 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -280,14 +280,15 @@ final class FirstLaunchHistory { static func validatedVersion(_ version: String?) -> String? { guard let version, (1...120).contains(version.utf8.count) else { return nil } let fullRange = NSRange(version.startIndex.. Date: Thu, 26 Nov 2026 16:41:06 +0800 Subject: [PATCH 5/7] fix(device-utils): harden reset, backup exclusion, and legacy seeding --- .../react-native-device-utils/README.md | 2 +- .../DeviceUtilsFirstLaunch.kt | 39 +++++++++------ .../FirstLaunchHistory.kt | 27 +++++++---- .../ReactNativeDeviceUtils.kt | 5 +- .../react-native-device-utils/docs/SPEC.md | 4 +- .../ios/DeviceUtilsFirstLaunch.swift | 40 +++++++++++----- .../ios/ReactNativeDeviceUtils.swift | 2 +- .../src/ReactNativeDeviceUtils.nitro.ts | 4 +- .../src/__tests__/firstLaunch.test.ts | 22 ++++++++- .../src/firstLaunch.native.ts | 9 ++-- .../src/firstLaunch.web.ts | 48 +++++++++++-------- 11 files changed, 132 insertions(+), 70 deletions(-) diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index ed5456523..4244a8b34 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -134,7 +134,7 @@ UI page; an MV3 service worker returns `false`. | `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. | | `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. | | `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. | -| `resetFirstLaunch()` | `void` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state. | +| `resetFirstLaunch()` | `boolean` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state; returns `false` if deletion fails. | | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise` / `Promise` / `Promise` | iOS, Android | Push-token plumbing; host setup still owns registration. | | `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. | | `getAndClearColdStartLocalNotification()` | `Promise` | iOS, Android | Returns local-notification JSON once; Android returns `""`. | diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt index 101b34587..18196d0eb 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt @@ -17,7 +17,7 @@ object DeviceUtilsFirstLaunch { private fun baseDirectory(context: Context): File? { val appContext = context.applicationContext ?: context - return appContext.noBackupFilesDir ?: appContext.filesDir + return appContext.noBackupFilesDir } /** @@ -84,38 +84,47 @@ object DeviceUtilsFirstLaunch { /** * Deletes persisted first-launch files and clears in-memory state so a subsequent * JS restart within the same native process observes a fresh launch. + * Returns true if persisted files were removed (or already absent), false on failure. */ @JvmStatic - fun reset(context: Context? = null) { + fun reset(context: Context): Boolean { synchronized(lock) { - if (context != null) { - baseDirectory(context)?.let { base -> - runCatching { File(base, FirstLaunchHistory.DIRECTORY_NAME).deleteRecursively() } + val base = baseDirectory(context) ?: return false + val storeDir = File(base, FirstLaunchHistory.DIRECTORY_NAME) + if (storeDir.exists()) { + val deleted = try { + storeDir.deleteRecursively() && !storeDir.exists() + } catch (_: SecurityException) { + false + } + if (!deleted) { + return false } } history = null + return true } } - internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean { - ensureInitialized(fallbackContext) - return history?.isFirstLaunch ?: false + internal fun isFirstLaunch(fallbackContext: Context? = null): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunch ?: false } - internal fun isFirstLaunchForCurrentAppVersion(fallbackContext: Context? = null): Boolean { - ensureInitialized(fallbackContext) - return history?.isFirstLaunchForCurrentAppVersion ?: false + internal fun isFirstLaunchForCurrentAppVersion(fallbackContext: Context? = null): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunchForCurrentAppVersion ?: false } internal fun isFirstLaunchForBundle( bundleVersion: String?, fallbackContext: Context? = null, - ): Boolean { - ensureInitialized(fallbackContext) - return history?.isFirstLaunchForBundle(bundleVersion) ?: false + ): Boolean = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.isFirstLaunchForBundle(bundleVersion) ?: false } - private fun ensureInitialized(fallbackContext: Context?) { + private fun ensureInitializedLocked(fallbackContext: Context?) { if (history == null && fallbackContext != null) { initialize(fallbackContext) } diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt index 4cb214bd9..75bade7a2 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -19,23 +19,30 @@ internal class FirstLaunchHistory( init { val launchedFile = File(storeDirectory, LAUNCHED_FILE_NAME) val launchedExists = launchedFile.exists() - isFirstLaunch = if (launchedExists) { - false - } else { - val wrote = writeString(launchedFile, "1") - wrote && !hasPreviousLaunch - } - val legacyBaseline = if (launchedExists) null else validatedVersion(previousAppVersion) val validCurrent = validatedVersion(appVersion) + val appVerFile = File(storeDirectory, APP_VERSION_FILE_NAME) + + // Seed or evaluate app_ver BEFORE writing `launched` so an interrupted + // startup never loses the legacy app-version baseline. isFirstLaunchForCurrentAppVersion = if (validCurrent != null) { evaluateVersionFile( - file = File(storeDirectory, APP_VERSION_FILE_NAME), + file = appVerFile, currentVersion = validCurrent, legacyBaseline = legacyBaseline, ) } else { + if (legacyBaseline != null && !appVerFile.exists()) { + writeString(appVerFile, legacyBaseline) + } + false + } + + isFirstLaunch = if (launchedExists) { false + } else { + val wrote = writeString(launchedFile, "1") + wrote && !hasPreviousLaunch } } @@ -84,8 +91,8 @@ internal class FirstLaunchHistory( if (isHigher) { return writeString(file, currentVersion) } - if (existing == null) { - writeString(file, baseline) + if (existing == null && legacyBaseline != null) { + writeString(file, legacyBaseline) } return false } diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 0e323e6f4..8e15a8b4c 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -55,8 +55,9 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven override fun isFirstLaunchForCurrentBundle(bundleVersion: String?): Boolean = DeviceUtilsFirstLaunch.isFirstLaunchForBundle(bundleVersion, NitroModules.applicationContext) - override fun resetFirstLaunch() { - DeviceUtilsFirstLaunch.reset(NitroModules.applicationContext) + override fun resetFirstLaunch(): Boolean { + val context = NitroModules.applicationContext ?: return false + return DeviceUtilsFirstLaunch.reset(context) } override fun getInMemoryValue(key: String): InMemoryValue? = InMemoryStore.get(key) diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 39adb43f0..c7c968c60 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -31,7 +31,7 @@ On each launch, startup reads the persisted entries, computes and freezes the cu | Android | Host calls `DeviceUtilsFirstLaunch.initialize(context, isLegacyInstall = { ... }, legacyAppVersion = { ... })` in `Application.onCreate()`. Lazy fallback initializes with `isLegacyInstall = false`. | `context.noBackupFilesDir/1k_first_launch/` (immune to Clear Cache and Auto Backup) | Owned by the host app (lambdas are only invoked when `launched` does not exist yet). | | Web / Desktop / Extension | Host calls `initFirstLaunch({ appVersion, bundleVersion, isLegacyInstall, legacyAppVersion })` once at UI startup before reading getters. | `localStorage` keys `1k_fl_launched`, `1k_fl_app_ver`, `1k_fl_bundle_ver` | Owned by the host app (e.g. sampled in an HTML `` script or Electron preload before app JS writes to storage). | -`resetFirstLaunch()` (and native `DeviceUtilsFirstLaunch.reset()`) removes the `1k_first_launch/` directory (or the 3 `localStorage` keys) **and clears the in-memory launch cache**, so a Reset App flow followed by a JS soft restart in the same native process observes a fresh launch. +`resetFirstLaunch(): boolean` (and native `DeviceUtilsFirstLaunch.reset()` on iOS / `DeviceUtilsFirstLaunch.reset(context)` on Android) removes the `1k_first_launch/` directory (or the 3 `localStorage` keys) **and clears the in-memory launch cache**, returning `true` when deletion succeeds (including already-absent entries) and `false` on failure so callers can retry before soft-restarting JS. Version strings must have a numeric dot-separated core with optional SemVer pre-release (`-...`) and build metadata (`+...`) suffixes (1–120 ASCII chars, e.g. `6.5.0`, `6.5.0-beta.1`, `1000`). Non-numeric cores such as `v6.5.0` are rejected. Version comparison compares numeric dot-separated segments by integer value (e.g. `6.10.0 > 6.5.0`, `1000 > 999`) with SemVer pre-release ordering (`6.5.0 > 6.5.0-beta.1`). A version strictly higher than the persisted highest version returns `true` for the current launch and advances the persisted entry. Rolling back to or running any version lower than or equal to the persisted highest version returns `false` and keeps the higher value persisted. @@ -45,7 +45,7 @@ The `@onekeyfe/react-native-device-utils/first-launch` entry point exposes: - `isFirstLaunch(): boolean` - `isFirstLaunchForCurrentAppVersion(appVersion?: string): boolean` - `isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean` -- `resetFirstLaunch(): void` +- `resetFirstLaunch(): boolean` React Native delegates to `ReactNativeDeviceUtils`. Web documents, Electron renderers, and extension-owned pages share `src/firstLaunch.web.ts` backed by `window.localStorage`. After `initFirstLaunch(...)` runs at startup, getters can be called with zero arguments to read the cached launch results. Server runtimes and MV3 service workers have no `window.localStorage` and return `false`. diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index 570e968ac..844c27baa 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -53,14 +53,21 @@ public final class DeviceUtilsFirstLaunch: NSObject { /// Deletes persisted first-launch files and clears in-memory state so a subsequent /// JS restart within the same native process observes a fresh launch. - @objc public static func reset() { + /// Returns true if persisted files were removed (or already absent), false on failure. + @objc @discardableResult public static func reset() -> Bool { lock.lock() defer { lock.unlock() } - if let directory = defaultDirectory() { - let storeDir = directory.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) - try? FileManager.default.removeItem(at: storeDir) + guard let directory = defaultDirectory() else { return false } + let storeDir = directory.appendingPathComponent(FirstLaunchHistory.directoryName, isDirectory: true) + if FileManager.default.fileExists(atPath: storeDir.path) { + do { + try FileManager.default.removeItem(at: storeDir) + } catch { + return false + } } history = nil + return true } static var value: Bool { @@ -117,24 +124,31 @@ final class FirstLaunchHistory { let launchedURL = dir.appendingPathComponent(Self.launchedFileName) let launchedExists = FileManager.default.fileExists(atPath: launchedURL.path) - if launchedExists { - isFirstLaunch = false - } else { - let wrote = Self.writeString("1", to: launchedURL, directory: dir) - isFirstLaunch = wrote && !hasPreviousLaunch - } - let legacyBaseline = launchedExists ? nil : Self.validatedVersion(previousAppVersion) + + // Seed or evaluate app_ver BEFORE writing `launched` so an interrupted + // startup never loses the legacy app-version baseline. + let appVerURL = dir.appendingPathComponent(Self.appVersionFileName) if let validCurrent = Self.validatedVersion(appVersion) { isFirstLaunchForCurrentAppVersion = Self.evaluateVersionFile( - at: dir.appendingPathComponent(Self.appVersionFileName), + at: appVerURL, directory: dir, currentVersion: validCurrent, legacyBaseline: legacyBaseline ) } else { + if let legacyBaseline, !FileManager.default.fileExists(atPath: appVerURL.path) { + _ = Self.writeString(legacyBaseline, to: appVerURL, directory: dir) + } isFirstLaunchForCurrentAppVersion = false } + + if launchedExists { + isFirstLaunch = false + } else { + let wrote = Self.writeString("1", to: launchedURL, directory: dir) + isFirstLaunch = wrote && !hasPreviousLaunch + } } func isFirstLaunchForBundle(_ bundleVersion: String?) -> Bool { @@ -196,7 +210,7 @@ final class FirstLaunchHistory { var dirURL = directory var values = URLResourceValues() values.isExcludedFromBackup = true - try? dirURL.setResourceValues(values) + try dirURL.setResourceValues(values) try Data(value.utf8).write(to: url, options: .atomic) return true } catch { diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 23651ac4b..12b288e38 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -95,7 +95,7 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { DeviceUtilsFirstLaunch.forBundle(bundleVersion) } - func resetFirstLaunch() throws { + func resetFirstLaunch() throws -> Bool { DeviceUtilsFirstLaunch.reset() } diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index e49e63d04..357c4ade1 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -158,8 +158,8 @@ export interface ReactNativeDeviceUtils isFirstLaunchForCurrentAppVersion(): boolean; /** First launch of a bundle version higher than any previously launched bundle. */ isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean; - /** Clears persisted first-launch files and in-memory state (e.g. on Reset App). */ - resetFirstLaunch(): void; + /** Clears persisted first-launch files and in-memory state (e.g. on Reset App). Returns false if deletion fails. */ + resetFirstLaunch(): boolean; // Process-owned primitive Map, shared by all runtimes and never persisted. getInMemoryValue(key: string): InMemoryValue | undefined; setInMemoryValue(key: string, value: InMemoryValue): void; diff --git a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts index a7f02fe21..73e9a58bc 100644 --- a/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts +++ b/native-modules/react-native-device-utils/src/__tests__/firstLaunch.test.ts @@ -120,12 +120,32 @@ it('clears both persisted keys and in-memory state on resetFirstLaunch', () => { expect(restarted.isFirstLaunchForCurrentBundle()).toBe(false); // Reset in the same runtime (e.g. Reset App + JS soft restart) - restarted.resetFirstLaunch(); + expect(restarted.resetFirstLaunch()).toBe(true); expect(restarted.isFirstLaunch()).toBe(false); restarted.initFirstLaunch({ appVersion: '6.5.0', bundleVersion: '1000' }); expect(restarted.isFirstLaunch()).toBe(true); expect(restarted.isFirstLaunchForCurrentAppVersion()).toBe(true); expect(restarted.isFirstLaunchForCurrentBundle()).toBe(true); + + // Reset returns false when storage deletion fails and preserves in-memory state. + storage.removeItem.mockImplementationOnce(() => { + throw new Error('Remove failed'); + }); + expect(restarted.resetFirstLaunch()).toBe(false); + expect(restarted.isFirstLaunch()).toBe(true); +}); + +it('preserves legacyAppVersion even when appVersion is omitted during initFirstLaunch', () => { + const storage = createStorage(); + const doc = openDocument(storage); + doc.initFirstLaunch({ isLegacyInstall: true, legacyAppVersion: '6.5.0' }); + expect(doc.isFirstLaunch()).toBe(false); + expect(storage.getItem('1k_fl_app_ver')).toBe('6.5.0'); + + const next = openDocument(storage); + next.initFirstLaunch({ appVersion: '6.5.0' }); + expect(next.isFirstLaunch()).toBe(false); + expect(next.isFirstLaunchForCurrentAppVersion()).toBe(false); }); it('does not touch storage before initFirstLaunch so legacy init is never consumed early', () => { diff --git a/native-modules/react-native-device-utils/src/firstLaunch.native.ts b/native-modules/react-native-device-utils/src/firstLaunch.native.ts index 2e8848360..be3dd78cd 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.native.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.native.ts @@ -46,7 +46,10 @@ export function isFirstLaunchForCurrentBundle( ); } -export function resetFirstLaunch(): void { - startupBundleVersion = undefined; - ReactNativeDeviceUtils.resetFirstLaunch(); +export function resetFirstLaunch(): boolean { + const removed = ReactNativeDeviceUtils.resetFirstLaunch(); + if (removed) { + startupBundleVersion = undefined; + } + return removed; } diff --git a/native-modules/react-native-device-utils/src/firstLaunch.web.ts b/native-modules/react-native-device-utils/src/firstLaunch.web.ts index bb255a88b..3ce506871 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.web.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.web.ts @@ -208,19 +208,10 @@ export function initFirstLaunch(options?: FirstLaunchInitOptions): void { const isLegacyInstall = options?.isLegacyInstall === true; const launchedRead = safeGet(storage, FIRST_LAUNCH_KEYS.launched); const isFreshStorage = launchedRead.ok && launchedRead.value === null; - - if (!launchedRead.ok) { - cachedFirstLaunch = false; - } else if (launchedRead.value === null) { - const wrote = safeSet(storage, FIRST_LAUNCH_KEYS.launched, '1'); - cachedFirstLaunch = wrote && !isLegacyInstall; - } else { - // Present ("1" or corrupted): not a first launch, do not overwrite. - cachedFirstLaunch = false; - } - const legacyBaseline = isFreshStorage ? options?.legacyAppVersion : undefined; + // Seed or evaluate app_ver BEFORE writing `launched`, so a legacy baseline is + // never lost even when `appVersion` is omitted or startup is interrupted. if (validAppVersion !== undefined) { cachedAppResults.set( validAppVersion, @@ -231,6 +222,11 @@ export function initFirstLaunch(options?: FirstLaunchInitOptions): void { legacyBaseline ) ); + } else if (isValidVersion(legacyBaseline)) { + const existingApp = safeGet(storage, FIRST_LAUNCH_KEYS.appVersion); + if (existingApp.ok && existingApp.value === null) { + safeSet(storage, FIRST_LAUNCH_KEYS.appVersion, legacyBaseline); + } } if (validBundleVersion !== undefined) { @@ -243,6 +239,16 @@ export function initFirstLaunch(options?: FirstLaunchInitOptions): void { ) ); } + + if (!launchedRead.ok) { + cachedFirstLaunch = false; + } else if (launchedRead.value === null) { + const wrote = safeSet(storage, FIRST_LAUNCH_KEYS.launched, '1'); + cachedFirstLaunch = wrote && !isLegacyInstall; + } else { + // Present ("1" or corrupted): not a first launch, do not overwrite. + cachedFirstLaunch = false; + } } export function isFirstLaunch(): boolean { @@ -304,16 +310,17 @@ export function isFirstLaunchForCurrentBundle( return result; } -export function resetFirstLaunch(): void { +export function resetFirstLaunch(): boolean { const storage = getStorage(); - if (storage) { - try { - storage.removeItem(FIRST_LAUNCH_KEYS.launched); - storage.removeItem(FIRST_LAUNCH_KEYS.appVersion); - storage.removeItem(FIRST_LAUNCH_KEYS.bundleVersion); - } catch { - // Ignore storage errors during reset. - } + if (!storage) { + return false; + } + try { + storage.removeItem(FIRST_LAUNCH_KEYS.launched); + storage.removeItem(FIRST_LAUNCH_KEYS.appVersion); + storage.removeItem(FIRST_LAUNCH_KEYS.bundleVersion); + } catch { + return false; } initialized = false; cachedFirstLaunch = false; @@ -321,4 +328,5 @@ export function resetFirstLaunch(): void { startupBundleVersion = undefined; cachedAppResults.clear(); cachedBundleResults.clear(); + return true; } From 497cc801c5cb669298daefcc18fdae8850c072e8 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 16:58:09 +0800 Subject: [PATCH 6/7] fix(device-utils): add initFirstLaunchForBundle for OTA reload bundle switching --- .../react-native-device-utils/README.md | 1 + .../DeviceUtilsFirstLaunch.kt | 8 +++++++ .../FirstLaunchHistory.kt | 18 +++++++++++---- .../ReactNativeDeviceUtils.kt | 4 ++++ .../ios/DeviceUtilsFirstLaunch.swift | 23 +++++++++++++++---- .../ios/ReactNativeDeviceUtils.swift | 4 ++++ .../src/ReactNativeDeviceUtils.nitro.ts | 2 ++ .../src/firstLaunch.native.ts | 17 +++----------- .../tests/InMemoryStoreTest.kt | 14 +++++++---- .../tests/main.swift | 14 +++++++---- 10 files changed, 71 insertions(+), 34 deletions(-) diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index 4244a8b34..d80972029 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -133,6 +133,7 @@ UI page; an MV3 service worker returns `false`. | `getStartupTime()` | `Promise` | iOS, Android | Native startup timestamp. | | `isFirstLaunch()` | `boolean` | iOS, Android | Synchronous first launch of the local installation, with a stable result for the native process. | | `isFirstLaunchForCurrentAppVersion()` | `boolean` | iOS, Android | First launch of a native release version higher than any previously launched version. | +| `initFirstLaunchForBundle(bundleVersion)` | `void` | iOS, Android | Records the executing bundle at JS startup / OTA reload as the active bundle identity. | | `isFirstLaunchForCurrentBundle(bundleVersion?)` | `boolean` | iOS, Android | First launch of a bundle version higher than any previously launched bundle. | | `resetFirstLaunch()` | `boolean` | iOS, Android | Clears persisted `1k_first_launch/` files and in-memory launch state; returns `false` if deletion fails. | | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise` / `Promise` / `Promise` | iOS, Android | Push-token plumbing; host setup still owns registration. | diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt index 18196d0eb..94581d142 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/DeviceUtilsFirstLaunch.kt @@ -116,6 +116,14 @@ object DeviceUtilsFirstLaunch { history?.isFirstLaunchForCurrentAppVersion ?: false } + internal fun initForBundle( + bundleVersion: String, + fallbackContext: Context? = null, + ) = synchronized(lock) { + ensureInitializedLocked(fallbackContext) + history?.initForBundle(bundleVersion) + } + internal fun isFirstLaunchForBundle( bundleVersion: String?, fallbackContext: Context? = null, diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt index 75bade7a2..9672ce401 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -14,7 +14,7 @@ internal class FirstLaunchHistory( val isFirstLaunchForCurrentAppVersion: Boolean private val storeDirectory = File(baseDirectory, DIRECTORY_NAME) private val bundleResults = mutableMapOf() - private var initialBundleVersion: String? = null + private var currentBundleVersion: String? = null init { val launchedFile = File(storeDirectory, LAUNCHED_FILE_NAME) @@ -46,15 +46,23 @@ internal class FirstLaunchHistory( } } + @Synchronized + fun initForBundle(bundleVersion: String) { + val validBundle = validatedVersion(bundleVersion) ?: return + currentBundleVersion = validBundle + resolveBundle(validBundle) + } + @Synchronized fun isFirstLaunchForBundle(bundleVersion: String?): Boolean { if (bundleVersion == null) { - return initialBundleVersion?.let { bundleResults[it] } ?: false + return currentBundleVersion?.let { bundleResults[it] } ?: false } val validBundle = validatedVersion(bundleVersion) ?: return false - if (initialBundleVersion == null) { - initialBundleVersion = validBundle - } + return resolveBundle(validBundle) + } + + private fun resolveBundle(validBundle: String): Boolean { bundleResults[validBundle]?.let { return it } diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 8e15a8b4c..3aa463960 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -52,6 +52,10 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven override fun isFirstLaunchForCurrentAppVersion(): Boolean = DeviceUtilsFirstLaunch.isFirstLaunchForCurrentAppVersion(NitroModules.applicationContext) + override fun initFirstLaunchForBundle(bundleVersion: String) { + DeviceUtilsFirstLaunch.initForBundle(bundleVersion, NitroModules.applicationContext) + } + override fun isFirstLaunchForCurrentBundle(bundleVersion: String?): Boolean = DeviceUtilsFirstLaunch.isFirstLaunchForBundle(bundleVersion, NitroModules.applicationContext) diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index 844c27baa..fb8caeefe 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -78,6 +78,10 @@ public final class DeviceUtilsFirstLaunch: NSObject { withHistory(default: false) { $0.isFirstLaunchForCurrentAppVersion } } + static func initForBundle(_ bundleVersion: String) { + withHistory(default: ()) { $0.initForBundle(bundleVersion) } + } + static func forBundle(_ bundleVersion: String?) -> Bool { withHistory(default: false) { $0.isFirstLaunchForBundle(bundleVersion) } } @@ -116,7 +120,7 @@ final class FirstLaunchHistory { let isFirstLaunchForCurrentAppVersion: Bool private let storeDirectory: URL private var bundleResults: [String: Bool] = [:] - private var initialBundleVersion: String? + private var currentBundleVersion: String? init(baseDirectory: URL, appVersion: String?, previousAppVersion: String?, hasPreviousLaunch: Bool) { let dir = baseDirectory.appendingPathComponent(Self.directoryName, isDirectory: true) @@ -151,16 +155,25 @@ final class FirstLaunchHistory { } } + func initForBundle(_ bundleVersion: String) { + guard let validBundle = Self.validatedVersion(bundleVersion) else { + return + } + currentBundleVersion = validBundle + _ = resolveBundle(validBundle) + } + func isFirstLaunchForBundle(_ bundleVersion: String?) -> Bool { guard let bundleVersion else { - return initialBundleVersion.flatMap { bundleResults[$0] } ?? false + return currentBundleVersion.flatMap { bundleResults[$0] } ?? false } guard let validBundle = Self.validatedVersion(bundleVersion) else { return false } - if initialBundleVersion == nil { - initialBundleVersion = validBundle - } + return resolveBundle(validBundle) + } + + private func resolveBundle(_ validBundle: String) -> Bool { if let cached = bundleResults[validBundle] { return cached } diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 12b288e38..ee81b3799 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -91,6 +91,10 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { DeviceUtilsFirstLaunch.forCurrentAppVersion } + func initFirstLaunchForBundle(bundleVersion: String) throws { + DeviceUtilsFirstLaunch.initForBundle(bundleVersion) + } + func isFirstLaunchForCurrentBundle(bundleVersion: String?) throws -> Bool { DeviceUtilsFirstLaunch.forBundle(bundleVersion) } diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 357c4ade1..08d39294e 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -156,6 +156,8 @@ export interface ReactNativeDeviceUtils isFirstLaunch(): boolean; /** First launch of a native release version higher than any previously launched version. */ isFirstLaunchForCurrentAppVersion(): boolean; + /** Records the executing bundle version at JS startup / OTA reload as the active bundle identity. */ + initFirstLaunchForBundle(bundleVersion: string): void; /** First launch of a bundle version higher than any previously launched bundle. */ isFirstLaunchForCurrentBundle(bundleVersion?: string): boolean; /** Clears persisted first-launch files and in-memory state (e.g. on Reset App). Returns false if deletion fails. */ diff --git a/native-modules/react-native-device-utils/src/firstLaunch.native.ts b/native-modules/react-native-device-utils/src/firstLaunch.native.ts index be3dd78cd..364d4d9d5 100644 --- a/native-modules/react-native-device-utils/src/firstLaunch.native.ts +++ b/native-modules/react-native-device-utils/src/firstLaunch.native.ts @@ -15,16 +15,11 @@ export interface FirstLaunchInitOptions { legacyAppVersion?: string; } -// Per-JS-runtime executing bundle identity: stays pinned during explicit lookups -// and automatically refreshes when a JS reload boots a new bundle version. -let startupBundleVersion: string | undefined; - export function initFirstLaunch(options?: FirstLaunchInitOptions): void { ReactNativeDeviceUtils.isFirstLaunch(); ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); if (options?.bundleVersion !== undefined) { - startupBundleVersion = options.bundleVersion; - ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(options.bundleVersion); + ReactNativeDeviceUtils.initFirstLaunchForBundle(options.bundleVersion); } } @@ -41,15 +36,9 @@ export function isFirstLaunchForCurrentAppVersion( export function isFirstLaunchForCurrentBundle( bundleVersion?: string ): boolean { - return ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle( - bundleVersion ?? startupBundleVersion - ); + return ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(bundleVersion); } export function resetFirstLaunch(): boolean { - const removed = ReactNativeDeviceUtils.resetFirstLaunch(); - if (removed) { - startupBundleVersion = undefined; - } - return removed; + return ReactNativeDeviceUtils.resetFirstLaunch(); } diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 1611bcf77..0b7000ffd 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -148,9 +148,9 @@ fun main() { val fresh = launch("6.5.0") check(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) check(!fresh.isFirstLaunchForBundle(null)) - check(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) - check(fresh.isFirstLaunchForBundle(null)) - // Explicit lookup of another bundle must not overwrite zero-arg startup bundle result. + fresh.initForBundle("1000") + check(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle(null)) + // Explicit lookup of another bundle must not overwrite zero-arg active bundle result. check(!fresh.isFirstLaunchForBundle("999")) check(fresh.isFirstLaunchForBundle(null)) // Reject non-numeric version core, trailing newlines, and traversal strings. @@ -160,10 +160,14 @@ fun main() { val restart = launch("6.5.0") check(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) - check(!restart.isFirstLaunchForBundle("1000")) - check(!restart.isFirstLaunchForBundle(null)) + restart.initForBundle("1000") + check(!restart.isFirstLaunchForBundle("1000") && !restart.isFirstLaunchForBundle(null)) + // Explicit lookup of a higher bundle must not overwrite active bundle. check(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) check(!restart.isFirstLaunchForBundle(null)) + // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. + restart.initForBundle("1001") + check(restart.isFirstLaunchForBundle(null)) val rollback = launch("6.5.0") check(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index 89490bbc1..dca459e7a 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -146,9 +146,9 @@ func testFirstLaunchHistory() throws { let fresh = launch("6.5.0") precondition(fresh.isFirstLaunch && fresh.isFirstLaunchForCurrentAppVersion) precondition(!fresh.isFirstLaunchForBundle(nil)) - precondition(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle("1000")) - precondition(fresh.isFirstLaunchForBundle(nil)) - // Explicit lookup of another bundle must not overwrite zero-arg startup bundle result. + fresh.initForBundle("1000") + precondition(fresh.isFirstLaunchForBundle("1000") && fresh.isFirstLaunchForBundle(nil)) + // Explicit lookup of another bundle must not overwrite zero-arg active bundle result. precondition(!fresh.isFirstLaunchForBundle("999")) precondition(fresh.isFirstLaunchForBundle(nil)) // Reject non-numeric version core, trailing newlines, and traversal strings. @@ -158,10 +158,14 @@ func testFirstLaunchHistory() throws { let restart = launch("6.5.0") precondition(!restart.isFirstLaunch && !restart.isFirstLaunchForCurrentAppVersion) - precondition(!restart.isFirstLaunchForBundle("1000")) - precondition(!restart.isFirstLaunchForBundle(nil)) + restart.initForBundle("1000") + precondition(!restart.isFirstLaunchForBundle("1000") && !restart.isFirstLaunchForBundle(nil)) + // Explicit lookup of a higher bundle must not overwrite active bundle. precondition(restart.isFirstLaunchForBundle("1001") && restart.isFirstLaunchForBundle("1001")) precondition(!restart.isFirstLaunchForBundle(nil)) + // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. + restart.initForBundle("1001") + precondition(restart.isFirstLaunchForBundle(nil)) let rollback = launch("6.5.0") precondition(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) From 72f1b1d7be4500885cc1d39acc8145a30b85979d Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:42:27 +0800 Subject: [PATCH 7/7] fix(device-utils): clear active bundle on invalid version and document activation contract --- native-modules/react-native-device-utils/README.md | 7 ++++--- .../nitro/reactnativedeviceutils/FirstLaunchHistory.kt | 6 ++++-- native-modules/react-native-device-utils/docs/SPEC.md | 3 ++- .../ios/DeviceUtilsFirstLaunch.swift | 5 +++-- .../react-native-device-utils/tests/InMemoryStoreTest.kt | 3 +++ native-modules/react-native-device-utils/tests/main.swift | 3 +++ 6 files changed, 19 insertions(+), 8 deletions(-) diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index d80972029..eb175e9b2 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -65,9 +65,10 @@ const { launchType, deepLink } = const startupTime = await ReactNativeDeviceUtils.getStartupTime(); const isFirstLaunch = ReactNativeDeviceUtils.isFirstLaunch(); const isFirstAppVersionLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentAppVersion(); -const isFirstBundleLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle( - process.env.BUNDLE_VERSION, -); +if (process.env.BUNDLE_VERSION) { + ReactNativeDeviceUtils.initFirstLaunchForBundle(process.env.BUNDLE_VERSION); +} +const isFirstBundleLaunch = ReactNativeDeviceUtils.isFirstLaunchForCurrentBundle(); // Claim a startup stage exactly once across runtimes. const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent( diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt index 9672ce401..ffdaeffa0 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/FirstLaunchHistory.kt @@ -48,9 +48,11 @@ internal class FirstLaunchHistory( @Synchronized fun initForBundle(bundleVersion: String) { - val validBundle = validatedVersion(bundleVersion) ?: return + val validBundle = validatedVersion(bundleVersion) currentBundleVersion = validBundle - resolveBundle(validBundle) + if (validBundle != null) { + resolveBundle(validBundle) + } } @Synchronized diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index c7c968c60..b658c6b98 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -11,7 +11,8 @@ Background process starts that run the normal native app bootstrap also count. | --- | --- | | `isFirstLaunch()` | The local app installation. | | `isFirstLaunchForCurrentAppVersion()` | The native app's release version (`CFBundleShortVersionString` on iOS, `versionName` on Android). Build number changes alone keep the same identity. | -| `isFirstLaunchForCurrentBundle(bundleVersion?: string)` | The unique version embedded in the executing JS bundle. Call at JS startup with that version for built-in and OTA bundles. | +| `initFirstLaunchForBundle(bundleVersion: string)` | Activates and records the executing JS bundle version at JS startup and after an OTA reload. Passing an invalid version clears the active bundle identity without writing disk state. Assumes all live JS runtimes in the process are version-locked and restarted together on OTA bundle switches. | +| `isFirstLaunchForCurrentBundle(bundleVersion?: string)` | Returns whether the active bundle (when omitted) or explicitly supplied bundle version is higher than any previously launched bundle. Does not change the active bundle identity. | ## Lifecycle, persistence, and platform behavior diff --git a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift index fb8caeefe..244c0c80d 100644 --- a/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift +++ b/native-modules/react-native-device-utils/ios/DeviceUtilsFirstLaunch.swift @@ -156,10 +156,11 @@ final class FirstLaunchHistory { } func initForBundle(_ bundleVersion: String) { - guard let validBundle = Self.validatedVersion(bundleVersion) else { + let validBundle = Self.validatedVersion(bundleVersion) + currentBundleVersion = validBundle + guard let validBundle else { return } - currentBundleVersion = validBundle _ = resolveBundle(validBundle) } diff --git a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt index 0b7000ffd..4fa397de6 100644 --- a/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt +++ b/native-modules/react-native-device-utils/tests/InMemoryStoreTest.kt @@ -168,6 +168,9 @@ fun main() { // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. restart.initForBundle("1001") check(restart.isFirstLaunchForBundle(null)) + // Invalid startup bundle clears the active bundle identity so zero-arg getter returns false. + restart.initForBundle("v1002") + check(!restart.isFirstLaunchForBundle(null)) val rollback = launch("6.5.0") check(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion) diff --git a/native-modules/react-native-device-utils/tests/main.swift b/native-modules/react-native-device-utils/tests/main.swift index dca459e7a..368773353 100644 --- a/native-modules/react-native-device-utils/tests/main.swift +++ b/native-modules/react-native-device-utils/tests/main.swift @@ -166,6 +166,9 @@ func testFirstLaunchHistory() throws { // In-process OTA reload calls initForBundle with the new executing bundle and updates zero-arg getter. restart.initForBundle("1001") precondition(restart.isFirstLaunchForBundle(nil)) + // Invalid startup bundle clears the active bundle identity so zero-arg getter returns false. + restart.initForBundle("v1002") + precondition(!restart.isFirstLaunchForBundle(nil)) let rollback = launch("6.5.0") precondition(!rollback.isFirstLaunch && !rollback.isFirstLaunchForCurrentAppVersion)