Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/react-native/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3927,7 +3927,7 @@ SPEC CHECKSUMS:
ReactNativeCaptureProtection: ac103d5f2311fc6cb7412b49ebdc821b845bf97a
ReactNativeCheckBiometricAuthChanged: 9028250455b331bd52a29bf8223ffd29c158e60f
ReactNativeDependencies: d3b7423ba1e52525e42085c8470109abde583d2e
ReactNativeDeviceUtils: 0664aa178122a925cd134c94b782ccfcc7d82b87
ReactNativeDeviceUtils: 9af5b27bca3c0f6649fba2f70e1022edac2bfcd4
ReactNativeGetRandomValues: a8dd2d44b9f13e6a7c5165bf6fbbbf16d422a388
ReactNativeImageCropPicker: bb1e798732909427df3f83f2d0159f815bacc773
ReactNativeJpush: 7e7958e03c904e0bcc1f45b38688f4ec3bfb823f
Expand Down
66 changes: 66 additions & 0 deletions example/react-native/smoke/README.md
Original file line number Diff line number Diff line change
@@ -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
```
102 changes: 102 additions & 0 deletions example/react-native/smoke/check-device-utils-install-info.py
Original file line number Diff line number Diff line change
@@ -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()
41 changes: 41 additions & 0 deletions example/react-native/smoke/device-utils-install-info.js
Original file line number Diff line number Diff line change
@@ -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 (
<Text accessibilityLabel={marker} style={{ margin: 48 }}>
{marker}
</Text>
);
}

AppRegistry.registerComponent(appName, () => InstallInfoSmokeTest);
9 changes: 8 additions & 1 deletion native-modules/react-native-device-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<WebViewPackageInfo>` / `Promise<GooglePlayServicesStatus>` | 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<InstallerPackageName>` | iOS 16.4+ / Android | Asynchronous installer source (StoreKit 2 `AppTransaction.shared` on iOS, `PackageManager` on Android). |
| `getInstallationTime()` | `Promise<number>` | iOS / Android | App installation timestamp in Unix epoch milliseconds. |
| `getAppleAdsAttributionToken()` | `Promise<string \| undefined>` | 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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1480,4 +1480,30 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
InstallerPackageName.UNKNOWN
}
}

override fun getInstallerPackageNameAsync(): Promise<InstallerPackageName> {
return Promise.async {
getInstallerPackageName()
}
}

override fun getInstallationTime(): Promise<Double> {
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()
}
}
}
90 changes: 90 additions & 0 deletions native-modules/react-native-device-utils/docs/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<InstallerPackageName>;
getInstallationTime(): Promise<number>;
```

- `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`)
Comment thread
huhuanming marked this conversation as resolved.
Resolved
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.
Loading
Loading