diff --git a/example/react-native/ios/Podfile.lock b/example/react-native/ios/Podfile.lock index b600a2cde..a28cb4e92 100644 --- a/example/react-native/ios/Podfile.lock +++ b/example/react-native/ios/Podfile.lock @@ -3927,7 +3927,7 @@ SPEC CHECKSUMS: ReactNativeCaptureProtection: ac103d5f2311fc6cb7412b49ebdc821b845bf97a ReactNativeCheckBiometricAuthChanged: 9028250455b331bd52a29bf8223ffd29c158e60f ReactNativeDependencies: d3b7423ba1e52525e42085c8470109abde583d2e - ReactNativeDeviceUtils: 0664aa178122a925cd134c94b782ccfcc7d82b87 + ReactNativeDeviceUtils: 9af5b27bca3c0f6649fba2f70e1022edac2bfcd4 ReactNativeGetRandomValues: a8dd2d44b9f13e6a7c5165bf6fbbbf16d422a388 ReactNativeImageCropPicker: bb1e798732909427df3f83f2d0159f815bacc773 ReactNativeJpush: 7e7958e03c904e0bcc1f45b38688f4ec3bfb823f diff --git a/example/react-native/smoke/README.md b/example/react-native/smoke/README.md new file mode 100644 index 000000000..d8a5aa59b --- /dev/null +++ b/example/react-native/smoke/README.md @@ -0,0 +1,66 @@ +# Android DeviceUtils install info smoke test + +Generate the workspace's native bindings, then build the example's release APK +with the smoke test as its JavaScript entry point. It calls the exported +DeviceUtils Nitro APIs in the example's React Native runtime. The example +also starts a background runtime, so its release APK needs `background.bundle`. + +```sh +yarn install --immutable +find native-modules native-views -mindepth 2 -maxdepth 2 -name nitro.json -print0 \ + | xargs -0 -n1 -P4 sh -c 'yarn --cwd "$(dirname "$1")" nitrogen' _ +yarn workspace @onekeyfe/react-native-device-utils prepare +cd example/react-native +mkdir -p android/app/src/main/assets +yarn exec react-native bundle --platform android --dev false --entry-file background.js \ + --bundle-output android/app/src/main/assets/background.bundle +cd android +ENTRY_FILE=smoke/device-utils-install-info.js \ + ./gradlew :app:assembleRelease -PreactNativeArchitectures=arm64-v8a +``` + +The command builds for ARM64. Set `reactNativeArchitectures` to `x86_64` +for an x86-64 emulator. On each unlocked emulator, install the APK and run +the check. Set `ANDROID_SERIAL` to select the emulator when multiple devices +are attached. Use API 29 and API 33 or newer to cover the legacy and modern +PackageManager paths. + +```sh +adb install -r -i com.android.shell app/build/outputs/apk/release/app-release.apk +python3 ../smoke/check-device-utils-install-info.py +``` + +The explicit installer exercises the `other` enum. A fresh install with no +installer recorded exercises `unknown`. The check compares the JavaScript +installer enum and epoch-millisecond timestamp with PackageManager, whose +dump reports the install time to whole seconds. The script launches and +queries the app as the foreground user. + +## Secondary-user regression check + +Use an API 34 emulator with `com.example` absent for all users. Create a +secondary user or use an existing secondary user on that clean emulator. +Run the commands from `example/react-native/android` and set `secondary_user` +to the ID shown by `adb shell pm list users`. + +```sh +secondary_user=10 +adb install --user 0 -i com.android.shell app/build/outputs/apk/release/app-release.apk +sleep 2 +adb shell pm install-existing --user "$secondary_user" com.example +adb shell dumpsys package com.example +``` + +Confirm that the `firstInstallTime` under `User 0` differs from the value +under the secondary user, then switch users. + +```sh +adb shell am switch-user "$secondary_user" +``` + +Unlock the emulator, wait for the secondary user's home screen to appear, +and run the check. + +```sh +python3 ../smoke/check-device-utils-install-info.py +``` diff --git a/example/react-native/smoke/check-device-utils-install-info.py b/example/react-native/smoke/check-device-utils-install-info.py new file mode 100644 index 000000000..191b6f8a8 --- /dev/null +++ b/example/react-native/smoke/check-device-utils-install-info.py @@ -0,0 +1,102 @@ +import re +import subprocess +import time +import xml.etree.ElementTree as ET + + +PACKAGE = "com.example" +MARKER = "DeviceUtilsInstallInfo: " +DUMP_PATH = "/data/local/tmp/device-utils-install-info.xml" +INSTALL_TIME = re.compile( + r"^[ ]*firstInstallTime=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})$", + re.MULTILINE, +) + + +def shell(*args): + return subprocess.check_output(["adb", "shell", *args], text=True, timeout=30) + + +def install_time_for_user(package_dump, user_id): + package_fields, *user_fields = re.split( + r"^[ \t]+User (\d+):[^\n]*\n", package_dump, flags=re.MULTILINE + ) + user_times = { + user: match.group(1) + for user, fields in zip(user_fields[::2], user_fields[1::2]) + if (match := INSTALL_TIME.search(fields)) + } + if user_times: + return user_times.get(user_id) + legacy_time = INSTALL_TIME.search(package_fields) + return legacy_time.group(1) if legacy_time else None + + +def bridge_result(user_id): + shell("am", "start", "--user", user_id, "-S", "-W", "-n", f"{PACKAGE}/.MainActivity") + deadline = time.monotonic() + 45 + while time.monotonic() < deadline: + shell("rm", "-f", DUMP_PATH) + if DUMP_PATH in shell("uiautomator", "dump", DUMP_PATH): + xml = shell("cat", DUMP_PATH) + shell("rm", "-f", DUMP_PATH) + for node in ET.fromstring(xml).iter("node"): + if node.get("package") != PACKAGE: + continue + label = node.get("content-desc") or node.get("text", "") + if label.startswith(MARKER): + result = label.removeprefix(MARKER) + if result != "pending": + return result + time.sleep(1) + raise SystemExit("No DeviceUtils result appeared in the example app") + + +def main(): + user_id = shell("am", "get-current-user").strip() + if not re.fullmatch(r"[0-9]+", user_id): + raise SystemExit(f"Could not identify the foreground Android user: {user_id!r}") + + packages = shell( + "cmd", "package", "list", "packages", "--user", user_id, "-i", PACKAGE + ) + installer = re.search( + rf"^package:{re.escape(PACKAGE)}[ \t]+installer=([^\r\n]*)$", + packages, + re.MULTILINE, + ) + package_dump = shell("dumpsys", "package", PACKAGE) + installed = install_time_for_user(package_dump, user_id) + if not installer or not installed: + raise SystemExit( + f"PackageManager did not report install info for {PACKAGE} in user {user_id}" + ) + + installer_package = installer.group(1).strip() + expected_installer = { + "com.android.vending": "playStore", + "com.huawei.appmarket": "huaweiAppGallery", + "null": "unknown", + "": "unknown", + }.get(installer_package, "other") + # dumpsys renders firstInstallTime in the device's local time, to whole seconds. + expected_seconds = int(shell("date", "-d", f"'{installed}'", "+%s")) + result = bridge_result(user_id) + if shell("am", "get-current-user").strip() != user_id: + raise SystemExit("The foreground Android user changed during the smoke test") + value = re.fullmatch(r"(\w+) ([1-9][0-9]*)", result) + if ( + not value + or value.group(1) != expected_installer + or int(value.group(2)) // 1000 != expected_seconds + ): + raise SystemExit( + f"Bridge returned {result!r}, expected {expected_installer} " + f"at {expected_seconds} epoch seconds" + ) + sdk = shell("getprop", "ro.build.version.sdk").strip() + print(f"API {sdk}, user {user_id}: bridge returned {result}, matching PackageManager") + + +if __name__ == "__main__": + main() diff --git a/example/react-native/smoke/device-utils-install-info.js b/example/react-native/smoke/device-utils-install-info.js new file mode 100644 index 000000000..1c169ef7f --- /dev/null +++ b/example/react-native/smoke/device-utils-install-info.js @@ -0,0 +1,41 @@ +import React, { useEffect, useState } from 'react'; +import { AppRegistry, Text } from 'react-native'; +import { ReactNativeDeviceUtils } from '@onekeyfe/react-native-device-utils'; +import { name as appName } from '../app.json'; + +function InstallInfoSmokeTest() { + const [result, setResult] = useState('pending'); + + useEffect(() => { + async function run() { + try { + const [installer, time] = await Promise.all([ + ReactNativeDeviceUtils.getInstallerPackageNameAsync(), + ReactNativeDeviceUtils.getInstallationTime(), + ]); + if ( + typeof installer !== 'string' || + !Number.isSafeInteger(time) || + time <= 0 + ) { + throw new Error( + 'Expected a string installer and a positive integer timestamp', + ); + } + setResult(`${installer} ${time}`); + } catch (error) { + setResult(`failed: ${String(error)}`); + } + } + void run(); + }, []); + + const marker = `DeviceUtilsInstallInfo: ${result}`; + return ( + + {marker} + + ); +} + +AppRegistry.registerComponent(appName, () => InstallInfoSmokeTest); diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index eb175e9b2..e86c8420e 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -147,13 +147,20 @@ UI page; an MV3 service worker returns `false`. | `setMainMenuConfig(config)` + command listeners | `void` / listener ID | iOS (iPadOS) | Rebuilds the iPadOS app menu; Android ignores it. | | `setNavigationBarAppearance(r, g, b, a, useDarkIcons)` | `void` | Android | Applies the navigation-bar color and icon style; no-op on iOS. | | `getCurrentWebViewPackageInfo()` / `isGooglePlayServicesAvailable()` | `Promise` / `Promise` | Android | WebView package and Play Services status. | -| `getAndroidChannel()` / `getInstallerPackageName()` | `AndroidChannel` / `InstallerPackageName` | Android | Distribution channel and installer source. | +| `getAndroidChannel()` / `getInstallerPackageName()` | `AndroidChannel` / `InstallerPackageName` | Android / iOS | Distribution channel and synchronous installer source (`getInstallerPackageName` is deprecated on iOS). | +| `getInstallerPackageNameAsync()` | `Promise` | iOS 16.4+ / Android | Asynchronous installer source (StoreKit 2 `AppTransaction.shared` on iOS, `PackageManager` on Android). | +| `getInstallationTime()` | `Promise` | iOS / Android | App installation timestamp in Unix epoch milliseconds. | +| `getAppleAdsAttributionToken()` | `Promise` | iOS 14.3+ / Android | Apple AdServices attribution token on iOS (`undefined` on Android). | | `markBootSuccess()` / `getConsecutiveBootFailCount()` / `incrementConsecutiveBootFailCount()` / `setConsecutiveBootFailCount(count)` / `getAndClearRecoveryAction()` | varies | iOS, Android | Boot-failure counter and one-shot recovery action. | | `exitApp()` | `void` | iOS, Android | Terminates the app process. | See [`src/ReactNativeDeviceUtils.nitro.ts`](src/ReactNativeDeviceUtils.nitro.ts) for full signatures, result types and enum values. +On iOS, `AppTransaction.shared` may require network connectivity. A genuine +App Store or TestFlight install can temporarily return `unknown` when the +transaction is unavailable or the user is signed out. + ## Platform support | Capability | iOS | Android | Web | diff --git a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec index b3144c857..425b47034 100644 --- a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec +++ b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec @@ -19,7 +19,10 @@ Pod::Spec.new do |s| "cpp/**/*.{hpp,cpp}", ] s.exclude_files = "ios/tests/**/*" - s.frameworks = "AdServices", "StoreKit" + s.frameworks = ["AdServices", "StoreKit"] + s.resource_bundles = { + "ReactNativeDeviceUtilsPrivacyInfo" => ["ios/PrivacyInfo.xcprivacy"], + } s.dependency 'React-jsi' s.dependency 'React-callinvoker' 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 ae926db10..5a7811129 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 @@ -1480,4 +1480,30 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven InstallerPackageName.UNKNOWN } } + + override fun getInstallerPackageNameAsync(): Promise { + return Promise.async { + getInstallerPackageName() + } + } + + override fun getInstallationTime(): Promise { + return Promise.async { + val context = NitroModules.applicationContext + ?: throw IllegalStateException("Application context is unavailable") + val packageName = context.packageName + val pm = context.packageManager + val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + pm.getPackageInfo(packageName, 0) + } + val firstInstallTime = packageInfo.firstInstallTime + if (firstInstallTime <= 0L) { + throw IllegalStateException("App installation time is invalid") + } + firstInstallTime.toDouble() + } + } } diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index f18647348..69a6a28ed 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -739,3 +739,93 @@ values, a coarse rule change, retry after a rejected report and store recreation, input validation, a timeout with late completion, and concurrent callers. Android native CI builds the Kotlin stub. Confirming real postbacks across windows requires an eligible ad attribution on a test device. + +# DeviceUtils: Install source and installation time + +## Purpose, scope, and non-goals + +`ReactNativeDeviceUtils` owns cross-platform install source detection and app +installation timestamp lookup so consumers do not depend on `expo-application` or +deprecated iOS receipt APIs for install attribution and channel checks. + +- Supported platforms: iOS 16.4+ and Android. +- Non-goals: StoreKit receipt refresh or Apple ID sign-in prompts, Google Play + Install Referrer IPC, and attribution reporting or retry orchestration (owned + by the host app). + +## Public API and defaults + +```ts +getInstallerPackageNameAsync(): Promise; +getInstallationTime(): Promise; +``` + +- `getInstallerPackageNameAsync()` resolves to one of + `'appStore' | 'testFlight' | 'other' | 'playStore' | 'huaweiAppGallery' | 'unknown'`. + It never rejects; unavailable or unverified native sources resolve to + `'unknown'`. +- `getInstallationTime()` resolves to the app's installation time as Unix epoch + milliseconds (`number`, matching `Date.now()`). It rejects if the platform + cannot read a valid positive finite timestamp. +- The existing synchronous `getInstallerPackageName()` remains available for + backwards compatibility, but is deprecated for iOS install-source checks + because `Bundle.main.appStoreReceiptURL` is deprecated in iOS 18 and can be + absent on valid App Store installs. + +## Lifecycle and concurrency + +- Each call runs independently with no retained state or cross-call caching. +- On iOS, `getInstallerPackageNameAsync()` runs asynchronously via Swift + concurrency (`Promise.async`), and `getInstallationTime()` runs off the main + thread on a utility dispatch queue (`Promise.parallel(.global(qos: .utility))`). +- On Android, both methods run asynchronously via `Promise.async` off the JS + thread. + +## Platform contract + +| Method | iOS (16.4+) | Android | +| --- | --- | --- | +| `getInstallerPackageNameAsync()` | Simulator returns `'unknown'`. Builds with `embedded.mobileprovision` return `'other'`. Otherwise reads StoreKit 2 `AppTransaction.shared` without requesting a refresh: `.verified` `.production` -> `'appStore'`, `.sandbox` -> `'testFlight'`, `.xcode` -> `'other'`; unverified or error -> `'unknown'`. | Delegates to `PackageManager.getInstallSourceInfo(packageName).installingPackageName` (API 30+) or `getInstallerPackageName` (API < 30): `com.android.vending` -> `'playStore'`, `com.huawei.appmarket` -> `'huaweiAppGallery'`, null/empty/error -> `'unknown'`, other -> `'other'`. | +| `getInstallationTime()` | Reads `FileAttributeKey.creationDate` of the app sandbox `Documents` directory and returns `timeIntervalSince1970 * 1000`. Rejects if missing or non-positive. | Reads `PackageInfo.firstInstallTime` (`PackageInfoFlags.of(0)` on API 33+, `0` on API < 33) and returns epoch milliseconds. Rejects if context/package info is unavailable or non-positive. | + +### Known divergences and privacy notes + +- **StoreKit availability**: [`AppTransaction.shared`](https://developer.apple.com/documentation/storekit/apptransaction/shared) + may require network connectivity and can throw if the transaction is + unavailable or the user is signed out. A real App Store or TestFlight + installation can therefore temporarily return `'unknown'`. The host owns + retry policy. +- **Installation timestamp semantics**: Android provides an OS-level + `firstInstallTime`; iOS has no dedicated install-time API and uses the sandbox + `Documents` directory `creationDate`, which matches `expo-application` + semantics. +- **Privacy manifest**: The DeviceUtils pod ships its own `PrivacyInfo.xcprivacy` + in the `ReactNativeDeviceUtilsPrivacyInfo` resource bundle. It declares + `NSPrivacyAccessedAPICategoryFileTimestamp` with reason `C617.1` for reading + metadata inside the app container, and + `NSPrivacyAccessedAPICategoryUserDefaults` with reason `CA92.1` for + app-local state stored in `UserDefaults.standard`. + +## Conformance and acceptance + +- Status: `Implemented` (runtime StoreKit 2 verification requires an on-device + App Store / TestFlight build). +- Contract: `src/ReactNativeDeviceUtils.nitro.ts`. +- Native implementations: `ios/ReactNativeDeviceUtils.swift` (links `StoreKit` + in `ReactNativeDeviceUtils.podspec`) and + `android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt`. +- Automated checks: + - iOS XCTest (`ios/tests/AppleAdsAttributionTests.swift` / + `InstallInfoTests.swift`) covers StoreKit 2 environment mapping + (`production`, `sandbox`, `xcode`, `nil`/error), embedded provisioning + override, simulator behavior, and off-main-thread `getInstallationTime()` + conversion and error rejection. + - Android Gradle build (`:onekeyfe_react-native-device-utils:assembleDebug`) + verifies Kotlin compilation and generated Nitro JNI bindings. + - The [Android bridge smoke test](../../../example/react-native/smoke/README.md) + awaits both public methods in a real React Native runtime and compares + their values with PackageManager on API levels below 33 and on API 33+. + The smoke test launches as the foreground Android user and uses that + user's install time when PackageManager reports it per user. + - TypeScript / Nitrogen build (`bob build`, `typecheck`, `lint`) verifies JS + and generated bindings. diff --git a/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy b/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy new file mode 100644 index 000000000..f956310e2 --- /dev/null +++ b/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy @@ -0,0 +1,25 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 553691287..397dcb5d2 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -1,5 +1,6 @@ import AdServices import NitroModules +import StoreKit import UIKit import ReactNativeNativeLogger import os @@ -408,8 +409,8 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { } func getInstallerPackageName() throws -> InstallerPackageName { - // Mirror react-native-device-info: distinguish AppStore / TestFlight / Other - // via receipt path and embedded mobileprovision. Simulator has neither. + // Legacy synchronous fallback using receipt path and embedded mobileprovision. + // Prefer getInstallerPackageNameAsync() which uses StoreKit 2 AppTransaction.shared. #if targetEnvironment(simulator) return .unknown #else @@ -424,6 +425,99 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { #endif } + enum AppleStoreEnvironment: Sendable, Equatable { + case production + case sandbox + case xcode + } + + func getInstallerPackageNameAsync() throws -> Promise { + #if targetEnvironment(simulator) + let isSimulator = true + #else + let isSimulator = false + #endif + let hasEmbeddedProvision = Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil + return Self.resolveInstallerPackageName( + isSimulator: isSimulator, + hasEmbeddedProvision: hasEmbeddedProvision + ) { + guard #available(iOS 16.0, *) else { + return nil + } + guard case .verified(let transaction) = try await AppTransaction.shared else { + return nil + } + switch transaction.environment { + case .production: + return .production + case .sandbox: + return .sandbox + case .xcode: + return .xcode + default: + return nil + } + } + } + + static func resolveInstallerPackageName( + isSimulator: Bool, + hasEmbeddedProvision: Bool, + environmentProvider: @escaping @Sendable () async throws -> AppleStoreEnvironment? + ) -> Promise { + if isSimulator { + return .resolved(withResult: .unknown) + } + if hasEmbeddedProvision { + return .resolved(withResult: .other) + } + return Promise.async { + do { + guard let environment = try await environmentProvider() else { + return .unknown + } + switch environment { + case .production: + return .appstore + case .sandbox: + return .testflight + case .xcode: + return .other + } + } catch { + OneKeyLog.warn("DeviceUtils", "getInstallerPackageNameAsync failed: \(error.localizedDescription)") + return .unknown + } + } + } + + func getInstallationTime() throws -> Promise { + return Self.resolveInstallationTime { + guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else { + throw RuntimeError.error(withMessage: "Unable to locate Documents directory") + } + // Uses Required Reason API NSPrivacyAccessedAPICategoryFileTimestamp (C617.1). + let attributes = try FileManager.default.attributesOfItem(atPath: documentsURL.path) + return attributes[.creationDate] as? Date + } + } + + static func resolveInstallationTime( + using provider: @escaping @Sendable () throws -> Date? + ) -> Promise { + return Promise.parallel(.global(qos: .utility)) { + guard let date = try provider() else { + throw RuntimeError.error(withMessage: "Unable to determine app installation time") + } + let timestampMs = date.timeIntervalSince1970 * 1000.0 + guard timestampMs.isFinite && timestampMs > 0 else { + throw RuntimeError.error(withMessage: "App installation time is invalid") + } + return timestampMs + } + } + func getAppleAdsAttributionToken() throws -> Promise { guard #available(iOS 14.3, *) else { return .resolved(withResult: nil) diff --git a/native-modules/react-native-device-utils/ios/tests/InstallInfoTests.swift b/native-modules/react-native-device-utils/ios/tests/InstallInfoTests.swift new file mode 100644 index 000000000..9d7ea9c82 --- /dev/null +++ b/native-modules/react-native-device-utils/ios/tests/InstallInfoTests.swift @@ -0,0 +1,127 @@ +import NitroModules +import XCTest +@testable import ReactNativeDeviceUtils + +final class InstallInfoTests: XCTestCase { + private enum StoreError: Error { + case unavailable + } + + func testInstallerMapsProductionToAppStore() async throws { + let promise = ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: false + ) { + .production + } + let installer = try await promise.await() + XCTAssertEqual(installer, .appstore) + } + + func testInstallerMapsSandboxToTestFlight() async throws { + let promise = ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: false + ) { + .sandbox + } + let installer = try await promise.await() + XCTAssertEqual(installer, .testflight) + } + + func testInstallerMapsXcodeToOther() async throws { + let promise = ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: false + ) { + .xcode + } + let installer = try await promise.await() + XCTAssertEqual(installer, .other) + } + + func testInstallerReturnsUnknownWhenUnverifiedOrError() async throws { + let nilResult = try await ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: false + ) { + nil + }.await() + XCTAssertEqual(nilResult, .unknown) + + let errorResult = try await ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: false + ) { + throw StoreError.unavailable + }.await() + XCTAssertEqual(errorResult, .unknown) + } + + func testInstallerPrioritizesSimulatorAndEmbeddedProvision() async throws { + let simResult = try await ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: true, + hasEmbeddedProvision: false + ) { + XCTFail("StoreKit should not be queried on simulator") + return .production + }.await() + XCTAssertEqual(simResult, .unknown) + + let adHocResult = try await ReactNativeDeviceUtils.resolveInstallerPackageName( + isSimulator: false, + hasEmbeddedProvision: true + ) { + XCTFail("StoreKit should not be queried when embedded.mobileprovision exists") + return .production + }.await() + XCTAssertEqual(adHocResult, .other) + } + + @MainActor + func testInstallationTimeResolvesEpochMillisOffMainThread() async throws { + XCTAssertTrue(Thread.isMainThread) + let expectedDate = Date(timeIntervalSince1970: 1_700_000_000.25) + let promise = ReactNativeDeviceUtils.resolveInstallationTime { + XCTAssertFalse(Thread.isMainThread) + return expectedDate + } + let timestampMs = try await promise.await() + XCTAssertEqual(timestampMs, 1_700_000_000_250.0, accuracy: 0.5) + } + + func testInstallationTimeRejectsMissingOrInvalidDate() async { + do { + _ = try await ReactNativeDeviceUtils.resolveInstallationTime { nil }.await() + XCTFail("Expected missing date to reject") + } catch { + XCTAssertEqual( + String(describing: error), + "Unable to determine app installation time" + ) + } + + do { + _ = try await ReactNativeDeviceUtils.resolveInstallationTime { + Date(timeIntervalSince1970: 0) + }.await() + XCTFail("Expected non-positive date to reject") + } catch { + XCTAssertEqual( + String(describing: error), + "App installation time is invalid" + ) + } + } + + func testInstallationTimePreservesProviderError() async { + do { + _ = try await ReactNativeDeviceUtils.resolveInstallationTime { + throw StoreError.unavailable + }.await() + XCTFail("Expected provider error to reject") + } catch { + XCTAssertEqual(error as? StoreError, .unavailable) + } + } +} 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 503893eac..881c308c9 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -207,7 +207,25 @@ export interface ReactNativeDeviceUtils // Android Channel & Installer getAndroidChannel(): AndroidChannel; + /** + * Synchronously reads the installer package name. + * @deprecated On iOS, prefer `getInstallerPackageNameAsync()` which uses + * StoreKit 2 `AppTransaction.shared` instead of the deprecated receipt URL. + */ getInstallerPackageName(): InstallerPackageName; + /** + * Asynchronously determines the install source. + * Uses StoreKit 2 `AppTransaction.shared` on iOS 16.4+ and PackageManager on Android. + * Resolves to `'unknown'` when the source cannot be verified. On iOS, StoreKit + * may require a network connection, so `'unknown'` can be temporary. + */ + getInstallerPackageNameAsync(): Promise; + /** + * Returns the app installation timestamp in Unix epoch milliseconds. + * Uses the sandbox Documents directory creation date on iOS and + * `PackageInfo.firstInstallTime` on Android. + */ + getInstallationTime(): Promise; /** Returns an AdServices token on iOS 14.3+, or undefined on unsupported platforms. */ getAppleAdsAttributionToken(): Promise;