From 166c694e2cb2e61f7bff315c10a4abb8252dbb71 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 14:09:43 +0800 Subject: [PATCH 1/5] feat(device-utils): add StoreKit 2 installer lookup and installation time APIs --- example/react-native/ios/Podfile.lock | 2 +- .../react-native-device-utils/README.md | 5 +- .../ReactNativeDeviceUtils.podspec | 2 +- .../ReactNativeDeviceUtils.kt | 26 ++++ .../react-native-device-utils/docs/SPEC.md | 77 +++++++++++ .../ios/ReactNativeDeviceUtils.swift | 98 +++++++++++++- .../ios/tests/InstallInfoTests.swift | 127 ++++++++++++++++++ .../src/ReactNativeDeviceUtils.nitro.ts | 17 +++ 8 files changed, 349 insertions(+), 5 deletions(-) create mode 100644 native-modules/react-native-device-utils/ios/tests/InstallInfoTests.swift diff --git a/example/react-native/ios/Podfile.lock b/example/react-native/ios/Podfile.lock index 79eb464e5..b600a2cde 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: d3d18adc9c517eee5d427fa7b68ed3a32da57622 + ReactNativeDeviceUtils: 0664aa178122a925cd134c94b782ccfcc7d82b87 ReactNativeGetRandomValues: a8dd2d44b9f13e6a7c5165bf6fbbbf16d422a388 ReactNativeImageCropPicker: bb1e798732909427df3f83f2d0159f815bacc773 ReactNativeJpush: 7e7958e03c904e0bcc1f45b38688f4ec3bfb823f diff --git a/native-modules/react-native-device-utils/README.md b/native-modules/react-native-device-utils/README.md index cb8ef84f5..ccd62fb33 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -90,7 +90,10 @@ values are native copies, not retained JS objects. | `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. | diff --git a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec index 4b4f98f10..0f8ce6b11 100644 --- a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec +++ b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec @@ -19,7 +19,7 @@ Pod::Spec.new do |s| "cpp/**/*.{hpp,cpp}", ] s.exclude_files = "ios/tests/**/*" - s.frameworks = "AdServices" + s.frameworks = ["AdServices", "StoreKit"] 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 54d8c887b..3d5247c92 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 @@ -1438,4 +1438,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 0701b0809..0293e06fc 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -486,3 +486,80 @@ non-empty string, an empty string, and a thrown error. Android native CI builds the Kotlin implementation and generated JNI bindings. The consumer's Android native harness verifies the result is JavaScript `undefined`. Real AdServices token issuance requires an on-device check. + +# 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 cached StoreKit 2 `AppTransaction.shared` (no refresh / no sign-in prompt): `.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 + +- **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**: iOS `FileAttributeKey.creationDate` is a Required Reason + API (`NSPrivacyAccessedAPICategoryFileTimestamp`, reason `C617.1`), which the + host app declares in `PrivacyInfo.xcprivacy`. + +## 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. + - TypeScript / Nitrogen build (`bob build`, `typecheck`, `lint`) verifies JS + and generated bindings. diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 4b52535c8..d21ba2a20 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 @@ -350,8 +351,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 @@ -366,6 +367,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 95388dd83..a84d3d834 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -155,7 +155,24 @@ 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. + */ + 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; From cf67eecafe8a71e80ea692600c532dd586f52f58 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:22:08 +0800 Subject: [PATCH 2/5] fix(device-utils): address install info review feedback --- example/react-native/ios/Podfile.lock | 2 +- example/react-native/smoke/README.md | 30 ++++++++ .../smoke/check-device-utils-install-info.py | 77 +++++++++++++++++++ .../smoke/device-utils-install-info.js | 41 ++++++++++ .../react-native-device-utils/README.md | 4 + .../ReactNativeDeviceUtils.podspec | 3 + .../react-native-device-utils/docs/SPEC.md | 17 +++- .../ios/PrivacyInfo.xcprivacy | 17 ++++ .../src/ReactNativeDeviceUtils.nitro.ts | 3 +- 9 files changed, 188 insertions(+), 6 deletions(-) create mode 100644 example/react-native/smoke/README.md create mode 100644 example/react-native/smoke/check-device-utils-install-info.py create mode 100644 example/react-native/smoke/device-utils-install-info.js create mode 100644 native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy 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..6ea3812af --- /dev/null +++ b/example/react-native/smoke/README.md @@ -0,0 +1,30 @@ +# 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. This entry point calls the +exported DeviceUtils Nitro APIs in the example's React Native runtime. + +```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/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 app/build/outputs/apk/release/app-release.apk +python3 ../smoke/check-device-utils-install-info.py +``` + +The check compares the JavaScript installer enum and the epoch-millisecond +timestamp with PackageManager's package listing and install time. The +PackageManager dump exposes the install time to whole seconds. 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..db3257a04 --- /dev/null +++ b/example/react-native/smoke/check-device-utils-install-info.py @@ -0,0 +1,77 @@ +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" + + +def shell(*args): + return subprocess.check_output(["adb", "shell", *args], text=True, timeout=30) + + +def bridge_result(): + shell("am", "start", "-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(): + packages = shell("cmd", "package", "list", "packages", "-i", PACKAGE) + installer = re.search( + rf"^package:{re.escape(PACKAGE)}[ \t]+installer=([^\r\n]*)$", + packages, + re.MULTILINE, + ) + package_dump = shell("dumpsys", "package", PACKAGE) + installed = re.search( + r"^[ \t]*firstInstallTime=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})$", + package_dump, + re.MULTILINE, + ) + if not installer or not installed: + raise SystemExit(f"PackageManager did not report install info for {PACKAGE}") + + 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.group(1)}'", "+%s")) + result = bridge_result() + 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}: 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 ccd62fb33..8db20c593 100644 --- a/native-modules/react-native-device-utils/README.md +++ b/native-modules/react-native-device-utils/README.md @@ -100,6 +100,10 @@ values are native copies, not retained JS objects. 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 0f8ce6b11..425b47034 100644 --- a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec +++ b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec @@ -20,6 +20,9 @@ Pod::Spec.new do |s| ] s.exclude_files = "ios/tests/**/*" 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/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 0293e06fc..45e7c15c7 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -532,18 +532,24 @@ getInstallationTime(): Promise; | Method | iOS (16.4+) | Android | | --- | --- | --- | -| `getInstallerPackageNameAsync()` | Simulator returns `'unknown'`. Builds with `embedded.mobileprovision` return `'other'`. Otherwise reads cached StoreKit 2 `AppTransaction.shared` (no refresh / no sign-in prompt): `.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'`. | +| `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**: iOS `FileAttributeKey.creationDate` is a Required Reason - API (`NSPrivacyAccessedAPICategoryFileTimestamp`, reason `C617.1`), which the - host app declares in `PrivacyInfo.xcprivacy`. +- **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. ## Conformance and acceptance @@ -561,5 +567,8 @@ getInstallationTime(): Promise; 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+. - 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..fe840a043 --- /dev/null +++ b/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy @@ -0,0 +1,17 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + + 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 a84d3d834..8d73f7b1d 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -164,7 +164,8 @@ export interface ReactNativeDeviceUtils /** * 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. + * Resolves to `'unknown'` when the source cannot be verified. On iOS, StoreKit + * may require a network connection, so `'unknown'` can be temporary. */ getInstallerPackageNameAsync(): Promise; /** From 62aace693eae698eb3ce0f6ccca5495c823e8977 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:27:26 +0800 Subject: [PATCH 3/5] docs(device-utils): make Android install info smoke test reproducible --- example/react-native/smoke/README.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/example/react-native/smoke/README.md b/example/react-native/smoke/README.md index 6ea3812af..a80419ab9 100644 --- a/example/react-native/smoke/README.md +++ b/example/react-native/smoke/README.md @@ -1,15 +1,20 @@ # 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. This entry point calls the -exported DeviceUtils Nitro APIs in the example's React Native runtime. +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/android +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 ``` @@ -21,10 +26,11 @@ are attached. Use API 29 and API 33 or newer to cover the legacy and modern PackageManager paths. ```sh -adb install -r app/build/outputs/apk/release/app-release.apk +adb install -r -i com.android.shell app/build/outputs/apk/release/app-release.apk python3 ../smoke/check-device-utils-install-info.py ``` -The check compares the JavaScript installer enum and the epoch-millisecond -timestamp with PackageManager's package listing and install time. The -PackageManager dump exposes the install time to whole seconds. +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. From 6ec829fc3dccfdb205a190b5dc863b5bed0f5810 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:41:30 +0800 Subject: [PATCH 4/5] fix(device-utils): address privacy and Android user review feedback --- example/react-native/smoke/README.md | 6 ++- .../smoke/check-device-utils-install-info.py | 49 ++++++++++++++----- .../react-native-device-utils/docs/SPEC.md | 6 ++- .../ios/PrivacyInfo.xcprivacy | 8 +++ 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/example/react-native/smoke/README.md b/example/react-native/smoke/README.md index a80419ab9..bb1df3a06 100644 --- a/example/react-native/smoke/README.md +++ b/example/react-native/smoke/README.md @@ -33,4 +33,8 @@ 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. +dump reports the install time to whole seconds. To check a secondary user, +make the installed APK available to that user with +`adb shell pm install-existing --user USER_ID com.example`. Switch to that +user and unlock the emulator before running the check. The script launches +and queries the app as the foreground user. diff --git a/example/react-native/smoke/check-device-utils-install-info.py b/example/react-native/smoke/check-device-utils-install-info.py index db3257a04..191b6f8a8 100644 --- a/example/react-native/smoke/check-device-utils-install-info.py +++ b/example/react-native/smoke/check-device-utils-install-info.py @@ -7,14 +7,33 @@ 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 bridge_result(): - shell("am", "start", "-S", "-W", "-n", f"{PACKAGE}/.MainActivity") +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) @@ -34,20 +53,24 @@ def bridge_result(): def main(): - packages = shell("cmd", "package", "list", "packages", "-i", PACKAGE) + 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 = re.search( - r"^[ \t]*firstInstallTime=(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})$", - package_dump, - re.MULTILINE, - ) + 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}") + raise SystemExit( + f"PackageManager did not report install info for {PACKAGE} in user {user_id}" + ) installer_package = installer.group(1).strip() expected_installer = { @@ -57,8 +80,10 @@ def main(): "": "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.group(1)}'", "+%s")) - result = bridge_result() + 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 @@ -70,7 +95,7 @@ def main(): f"at {expected_seconds} epoch seconds" ) sdk = shell("getprop", "ro.build.version.sdk").strip() - print(f"API {sdk}: bridge returned {result}, matching PackageManager") + print(f"API {sdk}, user {user_id}: bridge returned {result}, matching PackageManager") if __name__ == "__main__": diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 45e7c15c7..0a6b24be4 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -549,7 +549,9 @@ getInstallationTime(): Promise; - **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. + metadata inside the app container, and + `NSPrivacyAccessedAPICategoryUserDefaults` with reason `CA92.1` for + app-local state stored in `UserDefaults.standard`. ## Conformance and acceptance @@ -570,5 +572,7 @@ getInstallationTime(): Promise; - 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 index fe840a043..f956310e2 100644 --- a/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy +++ b/native-modules/react-native-device-utils/ios/PrivacyInfo.xcprivacy @@ -12,6 +12,14 @@ C617.1 + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + From 32440589f67eba944d288b6b0157b679b2a80466 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 18:09:48 +0800 Subject: [PATCH 5/5] docs(device-utils): make secondary-user smoke check deterministic --- example/react-native/smoke/README.md | 36 ++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/example/react-native/smoke/README.md b/example/react-native/smoke/README.md index bb1df3a06..d8a5aa59b 100644 --- a/example/react-native/smoke/README.md +++ b/example/react-native/smoke/README.md @@ -33,8 +33,34 @@ 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. To check a secondary user, -make the installed APK available to that user with -`adb shell pm install-existing --user USER_ID com.example`. Switch to that -user and unlock the emulator before running the check. The script launches -and queries the app as the foreground user. +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 +```