@mojro/react-native-gnss-tracking-health 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js ADDED
@@ -0,0 +1,125 @@
1
+ import trackingQualityMonitor, {
2
+ TrackingQualityMonitor,
3
+ } from "./TrackingQualityMonitor";
4
+ import {
5
+ configure,
6
+ getConfig,
7
+ resetConfig,
8
+ getThresholds,
9
+ getApiLevelThresholds,
10
+ } from "./config";
11
+ import GnssMonitor, { GnssMonitor as GnssMonitorClass } from "./gnssMonitor";
12
+ import { collectSystemHealth } from "./systemHealth";
13
+ import {
14
+ NEVER_SLEEPING_STATE,
15
+ getBackgroundSettingsStatus,
16
+ isIgnoringBatteryOptimizations,
17
+ openNeverSleepingApps,
18
+ openBackgroundRestrictionSettings,
19
+ openBatteryOptimizationSettings,
20
+ setNeverSleepingAppsConfirmed,
21
+ } from "./backgroundSettings";
22
+ import {
23
+ assessDeviceFitness,
24
+ getAndroidApiLevel,
25
+ getGnssCapabilityProfile,
26
+ scoreApiLevel,
27
+ } from "./deviceFitness";
28
+ import {
29
+ validateTimeAndTimezone,
30
+ isAutomaticDateTimeEnabled,
31
+ isClockSkewed,
32
+ getTimeDifferenceInMinutes,
33
+ openDateTimeSettings,
34
+ } from "./timeValidation";
35
+ import { normalizeLocation } from "./adapters/normalizeLocation";
36
+ import {
37
+ detectAbnormalTrace,
38
+ detectLocationThrottling,
39
+ getAccuracyMeters,
40
+ isGoodAccuracySample,
41
+ isMockedLocation,
42
+ isPoorTrackingSample,
43
+ locationTimestampMs,
44
+ } from "./traceAnalyzer";
45
+ import { useTrackingQuality } from "./hooks/useTrackingQuality";
46
+ import { useTrackingMonitor } from "./hooks/useTrackingMonitor";
47
+ import { useDeviceFitness } from "./hooks/useDeviceFitness";
48
+ import { useSystemHealth } from "./hooks/useSystemHealth";
49
+ import { useTimeValidation } from "./hooks/useTimeValidation";
50
+ import { useTrackingQualityAlerts } from "./hooks/useTrackingQualityAlerts";
51
+
52
+ export {
53
+ // Singleton + class
54
+ trackingQualityMonitor,
55
+ TrackingQualityMonitor,
56
+ // Config
57
+ configure,
58
+ getConfig,
59
+ resetConfig,
60
+ getThresholds,
61
+ getApiLevelThresholds,
62
+ // GNSS
63
+ GnssMonitor,
64
+ GnssMonitorClass,
65
+ // Independent modules
66
+ collectSystemHealth,
67
+ // Background restrictions (battery optimization + Samsung Never sleeping apps)
68
+ NEVER_SLEEPING_STATE,
69
+ getBackgroundSettingsStatus,
70
+ isIgnoringBatteryOptimizations,
71
+ openNeverSleepingApps,
72
+ openBackgroundRestrictionSettings,
73
+ openBatteryOptimizationSettings,
74
+ setNeverSleepingAppsConfirmed,
75
+ assessDeviceFitness,
76
+ getAndroidApiLevel,
77
+ getGnssCapabilityProfile,
78
+ scoreApiLevel,
79
+ validateTimeAndTimezone,
80
+ isAutomaticDateTimeEnabled,
81
+ openDateTimeSettings,
82
+ isClockSkewed,
83
+ getTimeDifferenceInMinutes,
84
+ // Traces
85
+ normalizeLocation,
86
+ detectAbnormalTrace,
87
+ detectLocationThrottling,
88
+ getAccuracyMeters,
89
+ isGoodAccuracySample,
90
+ isMockedLocation,
91
+ isPoorTrackingSample,
92
+ locationTimestampMs,
93
+ // Hooks
94
+ useTrackingQuality,
95
+ useTrackingMonitor,
96
+ useDeviceFitness,
97
+ useSystemHealth,
98
+ useTimeValidation,
99
+ useTrackingQualityAlerts,
100
+ };
101
+
102
+ export {
103
+ ALERT_TYPES,
104
+ ALERT_SEVERITY,
105
+ EVENT_NAMES,
106
+ API_LEVEL_THRESHOLDS,
107
+ DEFAULT_API_LEVEL_THRESHOLDS,
108
+ DEFAULT_THRESHOLDS,
109
+ DEVICE_FITNESS,
110
+ GNSS_CAPABILITY_BY_API,
111
+ MIN_SATELLITES_FOR_GOOD_FIX,
112
+ TRIP_START_SAT_WINDOW_MS,
113
+ POOR_TRACKING_DURATION_MS,
114
+ POOR_ACCURACY_THRESHOLD_M,
115
+ TELEPORT_IMPLIED_SPEED_KMH,
116
+ TELEPORT_MIN_JUMP_METERS,
117
+ EXPECTED_TRACE_INTERVAL_MS,
118
+ THROTTLE_GAP_MULTIPLIER,
119
+ THROTTLE_MIN_GAP_MS,
120
+ SYSTEM_CHECK_INTERVAL_MS,
121
+ ALERT_COOLDOWN_MS,
122
+ TIME_SKEW_THRESHOLD_MINUTES,
123
+ } from "./constants";
124
+
125
+ export default trackingQualityMonitor;
@@ -0,0 +1,116 @@
1
+ import { Platform } from "react-native";
2
+ import { getConfig, getThresholds } from "./config";
3
+ import { getLogger } from "./utils/logger";
4
+ import { validateTimeAndTimezone } from "./timeValidation";
5
+ import {
6
+ getBackgroundSettingsStatus,
7
+ isIgnoringBatteryOptimizations as nativeIsIgnoringBatteryOptimizations,
8
+ } from "./backgroundSettings";
9
+
10
+ async function safe(fn, fallback) {
11
+ if (typeof fn !== "function") {
12
+ return fallback;
13
+ }
14
+ try {
15
+ return await fn();
16
+ } catch (error) {
17
+ getLogger().warn("system check failed:", error?.message);
18
+ return fallback;
19
+ }
20
+ }
21
+
22
+ async function tryDeviceInfo() {
23
+ try {
24
+ // Optional peer — lazy require
25
+ // eslint-disable-next-line global-require, import/no-extraneous-dependencies
26
+ return require("react-native-device-info");
27
+ } catch (e) {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Collect OS / device health independently of any tracking library.
34
+ *
35
+ * Prefer configure({ getPowerSaveMode, isIgnoringBatteryOptimizations, ... }).
36
+ * Falls back to react-native-device-info when installed.
37
+ */
38
+ export async function collectSystemHealth() {
39
+ const cfg = getConfig();
40
+ const DeviceInfo = await tryDeviceInfo();
41
+
42
+ const [
43
+ powerSaveMode,
44
+ batteryOptimizationIgnored,
45
+ powerState,
46
+ batteryLevel,
47
+ timeValidation,
48
+ backgroundSettings,
49
+ ] = await Promise.all([
50
+ safe(cfg.getPowerSaveMode, false),
51
+ safe(async () => {
52
+ if (Platform.OS !== "android") return true;
53
+ if (typeof cfg.isIgnoringBatteryOptimizations === "function") {
54
+ return cfg.isIgnoringBatteryOptimizations();
55
+ }
56
+ // No host override: use the library's native PowerManager check.
57
+ const native = await nativeIsIgnoringBatteryOptimizations();
58
+ return native === null ? true : native;
59
+ }, true),
60
+ safe(
61
+ cfg.getPowerState ||
62
+ (DeviceInfo?.getPowerState
63
+ ? () => DeviceInfo.getPowerState()
64
+ : null),
65
+ null
66
+ ),
67
+ safe(
68
+ cfg.getBatteryLevel ||
69
+ (DeviceInfo?.getBatteryLevel
70
+ ? () => DeviceInfo.getBatteryLevel()
71
+ : null),
72
+ null
73
+ ),
74
+ safe(() => validateTimeAndTimezone(), {
75
+ autoDateTimeEnabled: null,
76
+ clockSkewed: false,
77
+ badTimeOrTimezone: false,
78
+ }),
79
+ safe(() => getBackgroundSettingsStatus(), null),
80
+ ]);
81
+
82
+ const lowPowerMode =
83
+ !!powerSaveMode ||
84
+ powerState?.lowPowerMode === true ||
85
+ powerState?.batteryState === "unknown";
86
+
87
+ const backgroundTrackingRestricted =
88
+ Platform.OS === "android" && batteryOptimizationIgnored === false;
89
+
90
+ return {
91
+ platform: Platform.OS,
92
+ powerSaveMode: !!powerSaveMode,
93
+ lowPowerMode,
94
+ batteryOptimizationEnabled:
95
+ Platform.OS === "android" ? batteryOptimizationIgnored === false : false,
96
+ batteryOptimizationIgnored: !!batteryOptimizationIgnored,
97
+ batteryLevel:
98
+ typeof batteryLevel === "number" ? Math.round(batteryLevel * 100) : null,
99
+ lowBatteryMode: !!(
100
+ powerState?.lowPowerMode ||
101
+ (typeof batteryLevel === "number" &&
102
+ batteryLevel < getThresholds().lowBatteryFraction &&
103
+ !powerState?.batteryState?.includes?.("charging"))
104
+ ),
105
+ autoDateTimeEnabled: timeValidation.autoDateTimeEnabled,
106
+ clockSkewed: timeValidation.clockSkewed === true,
107
+ badTimeOrTimezone: !!timeValidation.badTimeOrTimezone,
108
+ timeValidation,
109
+ backgroundTrackingRestricted,
110
+ manufacturer: backgroundSettings?.manufacturer ?? null,
111
+ isSamsung: !!backgroundSettings?.isSamsung,
112
+ // Diagnostic only: never feeds device fitness (cannot be verified).
113
+ neverSleepingApps: backgroundSettings?.neverSleepingApps ?? null,
114
+ checkedAt: Date.now(),
115
+ };
116
+ }
@@ -0,0 +1,174 @@
1
+ import { NativeModules, Platform } from "react-native";
2
+ import { TIME_SKEW_THRESHOLD_MINUTES } from "./constants";
3
+ import { getConfig, getThresholds } from "./config";
4
+
5
+ const FETCH_TIMEOUT_MS = 10000;
6
+
7
+ const DEFAULT_TIME_SOURCES = [
8
+ () => fetchTimeFromDateHeader("https://www.apple.com"),
9
+ () => fetchTimeFromDateHeader("https://www.google.com"),
10
+ () => fetchTimeFromDateHeader("https://www.cloudflare.com/cdn-cgi/trace"),
11
+ ];
12
+
13
+ function parseDateHeader(response) {
14
+ const dateHeader = response?.headers?.get?.("date");
15
+ if (!dateHeader) {
16
+ return null;
17
+ }
18
+ const serverDate = new Date(dateHeader);
19
+ return Number.isNaN(serverDate.getTime()) ? null : serverDate;
20
+ }
21
+
22
+ async function fetchWithTimeout(url, options = {}, timeoutMs = FETCH_TIMEOUT_MS) {
23
+ const abortController = new AbortController();
24
+ const timeoutId = setTimeout(() => abortController.abort(), timeoutMs);
25
+ try {
26
+ return await fetch(url, {
27
+ ...options,
28
+ signal: abortController.signal,
29
+ });
30
+ } finally {
31
+ clearTimeout(timeoutId);
32
+ }
33
+ }
34
+
35
+ async function fetchTimeFromDateHeader(url) {
36
+ try {
37
+ let response = await fetchWithTimeout(url, { method: "HEAD" });
38
+ if (!response || response.status === 405 || response.status === 501) {
39
+ response = await fetchWithTimeout(url, { method: "GET" });
40
+ }
41
+ if (!response) {
42
+ return null;
43
+ }
44
+ return parseDateHeader(response);
45
+ } catch (error) {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ function getDifferenceInMinutes(serverTime, deviceTime = new Date()) {
51
+ return Math.abs(deviceTime.getTime() - serverTime.getTime()) / (1000 * 60);
52
+ }
53
+
54
+ /**
55
+ * Library (or host) AutoDateTime native module — separate from battery settings.
56
+ */
57
+ function getAutoDateTimeNative() {
58
+ if (Platform.OS !== "android") {
59
+ return null;
60
+ }
61
+ return NativeModules.AutoDateTime || null;
62
+ }
63
+
64
+ /**
65
+ * Returns `true` when Android automatic date & time AND automatic time zone are enabled.
66
+ * Returns `false` when either toggle is off.
67
+ * Returns `null` when unavailable (iOS, missing bridge, or error).
68
+ *
69
+ * Resolution order:
70
+ * 1) configure({ isAutomaticDateTimeEnabled }) — optional host override
71
+ * 2) NativeModules.AutoDateTime (library autodatetime package, or host module)
72
+ */
73
+ export async function isAutomaticDateTimeEnabled() {
74
+ const configured = getConfig().isAutomaticDateTimeEnabled;
75
+ if (typeof configured === "function") {
76
+ try {
77
+ const status = await configured();
78
+ return status == null ? null : Boolean(status);
79
+ } catch (e) {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ if (Platform.OS !== "android") {
85
+ return null;
86
+ }
87
+
88
+ const autoDateTime = getAutoDateTimeNative();
89
+ if (typeof autoDateTime?.isAutoDateTimeEnabled !== "function") {
90
+ return null;
91
+ }
92
+ try {
93
+ const status = await autoDateTime.isAutoDateTimeEnabled();
94
+ return Boolean(status);
95
+ } catch (error) {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Opens Android Date & time settings via AutoDateTime native module.
102
+ * Resolves false on iOS / when the module is missing.
103
+ */
104
+ export async function openDateTimeSettings() {
105
+ if (Platform.OS !== "android") {
106
+ return false;
107
+ }
108
+ const native = getAutoDateTimeNative();
109
+ if (typeof native?.openDateTimeSettings !== "function") {
110
+ return false;
111
+ }
112
+ try {
113
+ return !!(await native.openDateTimeSettings());
114
+ } catch (e) {
115
+ return false;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Compares device time against public HTTP Date headers.
121
+ * Matches driver-app `getTimeDifferenceInMinutes` semantics:
122
+ * - `false` as soon as any source is within the threshold (device time OK)
123
+ * - `true` only when every configured source responds AND all are skewed
124
+ * - `null` when checks are inconclusive (some/all sources unavailable)
125
+ */
126
+ export async function isClockSkewed({
127
+ thresholdMinutes = getThresholds().timeSkewThresholdMinutes,
128
+ sources = DEFAULT_TIME_SOURCES,
129
+ } = {}) {
130
+ let failedChecks = 0;
131
+
132
+ for (const source of sources) {
133
+ const serverTime = await source().catch(() => null);
134
+ if (!serverTime) {
135
+ continue;
136
+ }
137
+
138
+ if (getDifferenceInMinutes(serverTime) <= thresholdMinutes) {
139
+ return false;
140
+ }
141
+ failedChecks += 1;
142
+ }
143
+
144
+ return failedChecks === sources.length ? true : null;
145
+ }
146
+
147
+ /** @deprecated Prefer isClockSkewed — kept for parity with host app naming. */
148
+ export async function getTimeDifferenceInMinutes(options) {
149
+ return isClockSkewed(options);
150
+ }
151
+
152
+ /**
153
+ * Full time / timezone validation — AutoDateTime native (Android) + HTTP skew.
154
+ * Host apps consume these flags only.
155
+ */
156
+ export async function validateTimeAndTimezone(options = {}) {
157
+ const [autoDateTimeEnabled, clockSkewed] = await Promise.all([
158
+ isAutomaticDateTimeEnabled(),
159
+ isClockSkewed(options),
160
+ ]);
161
+
162
+ return {
163
+ platform: Platform.OS,
164
+ autoDateTimeEnabled,
165
+ clockSkewed: clockSkewed === true,
166
+ clockSkewCheckInconclusive: clockSkewed === null,
167
+ badTimeOrTimezone: autoDateTimeEnabled === false || clockSkewed === true,
168
+ thresholdMinutes:
169
+ options.thresholdMinutes ?? getThresholds().timeSkewThresholdMinutes,
170
+ checkedAt: Date.now(),
171
+ };
172
+ }
173
+
174
+ export { TIME_SKEW_THRESHOLD_MINUTES };
@@ -0,0 +1,100 @@
1
+ import { getDistanceInMeters } from "./utils/distance";
2
+ import { getThresholds } from "./config";
3
+ import { normalizeLocation } from "./adapters/normalizeLocation";
4
+
5
+ const MIN_SPEED_DT_HOURS = 1 / 3600;
6
+
7
+ export function locationTimestampMs(location) {
8
+ const normalized = location?.coords ? location : normalizeLocation(location);
9
+ if (normalized?.timestamp == null) {
10
+ return Date.now();
11
+ }
12
+ const ms = new Date(normalized.timestamp).getTime();
13
+ return Number.isFinite(ms) ? ms : Date.now();
14
+ }
15
+
16
+ export function isMockedLocation(location) {
17
+ const normalized = location?.coords ? location : normalizeLocation(location);
18
+ return !!(normalized?.mock || normalized?.coords?.mocked);
19
+ }
20
+
21
+ export function getAccuracyMeters(location) {
22
+ const normalized = location?.coords ? location : normalizeLocation(location);
23
+ const accuracy = Number(normalized?.coords?.accuracy);
24
+ return Number.isFinite(accuracy) ? accuracy : null;
25
+ }
26
+
27
+ export function detectAbnormalTrace(previous, next) {
28
+ const prev = previous?.coords ? previous : normalizeLocation(previous);
29
+ const nxt = next?.coords ? next : normalizeLocation(next);
30
+ if (!prev?.coords || !nxt?.coords) {
31
+ return null;
32
+ }
33
+
34
+ const {
35
+ teleportMinJumpMeters,
36
+ teleportImpliedSpeedKmh,
37
+ } = getThresholds();
38
+
39
+ const distanceM = getDistanceInMeters(
40
+ prev.coords.latitude,
41
+ prev.coords.longitude,
42
+ nxt.coords.latitude,
43
+ nxt.coords.longitude
44
+ );
45
+
46
+ const dtMs = Math.max(locationTimestampMs(nxt) - locationTimestampMs(prev), 0);
47
+ const dtHours = Math.max(dtMs / 3600000, MIN_SPEED_DT_HOURS);
48
+ const speedKmh = distanceM / 1000 / dtHours;
49
+
50
+ if (
51
+ distanceM >= teleportMinJumpMeters &&
52
+ speedKmh >= teleportImpliedSpeedKmh
53
+ ) {
54
+ return {
55
+ kind: "teleport",
56
+ distanceM,
57
+ speedKmh,
58
+ dtMs,
59
+ };
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ /**
66
+ * Good horizontal accuracy: meters ≤ threshold (lower is better).
67
+ */
68
+ export function isGoodAccuracySample(accuracyM) {
69
+ const { poorAccuracyThresholdM } = getThresholds();
70
+ return accuracyM != null && accuracyM <= poorAccuracyThresholdM;
71
+ }
72
+
73
+ export function isPoorTrackingSample({ accuracyM, satellitesVisible }) {
74
+ const { poorAccuracyThresholdM, minSatellitesForGoodFix } = getThresholds();
75
+ const poorAccuracy =
76
+ accuracyM != null && accuracyM > poorAccuracyThresholdM;
77
+ const lowSats =
78
+ satellitesVisible != null && satellitesVisible < minSatellitesForGoodFix;
79
+ return poorAccuracy || lowSats;
80
+ }
81
+
82
+ export function detectLocationThrottling(lastTraceAt, now = Date.now()) {
83
+ if (!lastTraceAt) {
84
+ return null;
85
+ }
86
+ const {
87
+ throttleMinGapMs,
88
+ expectedTraceIntervalMs,
89
+ throttleGapMultiplier,
90
+ } = getThresholds();
91
+ const gapMs = now - lastTraceAt;
92
+ const threshold = Math.max(
93
+ throttleMinGapMs,
94
+ expectedTraceIntervalMs * throttleGapMultiplier
95
+ );
96
+ if (gapMs >= threshold) {
97
+ return { gapMs, thresholdMs: threshold };
98
+ }
99
+ return null;
100
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Haversine distance in meters (no host-app map utils dependency).
3
+ */
4
+ export function getDistanceInMeters(lat1, lon1, lat2, lon2) {
5
+ const R = 6371000;
6
+ const dLat = ((lat2 - lat1) * Math.PI) / 180;
7
+ const dLon = ((lon2 - lon1) * Math.PI) / 180;
8
+ const a =
9
+ Math.sin(dLat / 2) * Math.sin(dLat / 2) +
10
+ Math.cos((lat1 * Math.PI) / 180) *
11
+ Math.cos((lat2 * Math.PI) / 180) *
12
+ Math.sin(dLon / 2) *
13
+ Math.sin(dLon / 2);
14
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
15
+ return R * c;
16
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Default console logger. Host apps can override via configure({ logger }).
3
+ */
4
+ const defaultLogger = {
5
+ log: (...args) => {
6
+ if (typeof console !== "undefined" && console.log) {
7
+ console.log("[TrackingQuality]", ...args);
8
+ }
9
+ },
10
+ warn: (...args) => {
11
+ if (typeof console !== "undefined" && console.warn) {
12
+ console.warn("[TrackingQuality]", ...args);
13
+ }
14
+ },
15
+ error: (...args) => {
16
+ if (typeof console !== "undefined" && console.error) {
17
+ console.error("[TrackingQuality]", ...args);
18
+ }
19
+ },
20
+ };
21
+
22
+ let activeLogger = defaultLogger;
23
+
24
+ export function setLogger(logger) {
25
+ if (!logger) {
26
+ activeLogger = defaultLogger;
27
+ return;
28
+ }
29
+ activeLogger = {
30
+ log: logger.log || defaultLogger.log,
31
+ warn: logger.warn || defaultLogger.warn,
32
+ error: logger.error || defaultLogger.error,
33
+ };
34
+ }
35
+
36
+ export function getLogger() {
37
+ return activeLogger;
38
+ }