Skip to content

Colota - Android GPS Location tracker

Add Android 17+ local network permission handling

Max Dietrichf39b2c879af4
diff --git a/README.md b/README.md
index fd9b384a..c6f416b8 100644
--- a/README.md
+++ b/README.md
@@ -82,5 +82,3 @@ See the [Contributing Guide](https://colota.app/docs/contributing) for details o
- [GitHub Issues](https://github.com/dietrichmax/colota/issues)
- [GitHub Discussions](https://github.com/dietrichmax/colota/discussions)
-- [GitHub Sponsors](https://github.com/sponsors/dietrichmax)
-- [Ko-fi](https://ko-fi.com/maxdietrich)
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index 86c02385..3d87e190 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -20,6 +20,10 @@ Your server endpoint must accept HTTPS requests (POST or GET depending on your H
- `192.168.x.x`
- `10.x.x.x`
- `172.16.x.x – 172.31.x.x`
+- `100.64.x.x – 100.127.x.x` (CGNAT)
+- `169.254.x.x` (link-local)
+
+On **Android 17+**, connecting to another device on the local network (everything above except `localhost`) requires the **Nearby Wi-Fi Devices** permission. Colota requests this when you use **Test Connection**. See [Permissions](/docs/development/permissions#local-network-nearby-wi-fi-devices) for details.
Use the **Test Connection** button in settings to verify your server is reachable.
diff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.md
index fa39d53d..d89121d8 100644
--- a/apps/docs/docs/development/permissions.md
+++ b/apps/docs/docs/development/permissions.md
@@ -18,6 +18,7 @@ These are the permissions Colota uses and why. None are related to analytics, ad
| Network State | Yes | Check connectivity before syncing |
| Boot Completed | Yes | Auto-restart tracking after device reboot |
| Notifications | Android 13+ | Display the foreground service notification |
+| Nearby Wi-Fi Devices | Android 17+ | Access local network servers (self-hosted) |
| Battery Optimization Exemption | Optional | Prevent Android from killing the tracking service |
## Permission Request Flow
@@ -31,6 +32,8 @@ When you start tracking for the first time, Colota requests permissions in seque
If any required permission is denied, tracking cannot start. The app does not request permissions until you explicitly tap "Start Tracking".
+The **Local Network Permission** (Android 17+) is not part of this sequence. It is requested separately when you use **Test Connection** with a local/private server endpoint.
+
## Detailed Explanations
### Location Permissions
@@ -77,6 +80,14 @@ android.permission.POST_NOTIFICATIONS
Starting with Android 13, apps must request notification permission explicitly. Colota needs this for the foreground service notification. If denied, the service may still run but with reduced reliability depending on the Android version.
+### Local Network (Nearby Wi-Fi Devices)
+
+```
+android.permission.NEARBY_WIFI_DEVICES
+```
+
+Starting with Android 17, apps need this permission to connect to other devices on the local network. Colota requests it when you use **Test Connection** with a private/local IP endpoint (e.g. `192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, or `100.64.x.x`). Loopback addresses (`localhost` / `127.0.0.1`) do not require this permission. The `neverForLocation` flag is set, indicating this permission is not used to derive location, only for network access. If your server is a public HTTPS endpoint, this permission is never requested.
+
### Battery Optimization
```
diff --git a/apps/docs/docs/faq.md b/apps/docs/docs/faq.md
index d5b1d3db..588a431d 100644
--- a/apps/docs/docs/faq.md
+++ b/apps/docs/docs/faq.md
@@ -45,3 +45,7 @@ Depends on your settings. With the **Balanced** preset (30s interval, batch sync
### What Android versions are supported?
Colota requires Android 8.0 (API 26) or higher.
+
+### Why does Colota ask for "Nearby devices" permission?
+
+On Android 17+, apps need the Nearby Wi-Fi Devices permission to connect to local network addresses. Colota only requests this when your server is on a private/local IP (e.g. `192.168.x.x`). It is not used for device scanning or discovery, only to reach your self-hosted server.
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index 23171945..9cefca68 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -25,7 +25,7 @@ sidebar_position: 4
4. Verify network connectivity
5. Check the queue count in **Data Management**
-**Common causes**: Wrong URL, HTTPS required for non-localhost, expired SSL certificate, incorrect authentication, mismatched field mapping, self-signed certificate (not supported), **Wi-Fi Only Sync** enabled while on cellular data.
+**Common causes**: Wrong URL, HTTPS required for non-localhost, expired SSL certificate, incorrect authentication, mismatched field mapping, self-signed certificate (not supported), **Wi-Fi Only Sync** enabled while on cellular data, missing local network permission on Android 17+.
## Debugging with adb logcat
@@ -47,6 +47,18 @@ Key log tags:
You can also use the **Location History** screen in the app to see recorded locations on a track map or as a list with their accuracy and timestamps.
+## Local server not reachable (Android 17+)
+
+On Android 17 and later, connecting to local/private network addresses requires the **Nearby Wi-Fi Devices** permission. Colota requests this automatically when you test a local endpoint.
+
+If sync to a local server stopped working after an Android update:
+
+1. Go to **Android Settings > Apps > Colota > Permissions**
+2. Grant the **Nearby devices** permission
+3. Use the **Test Connection** button to verify
+
+If you denied the permission and the system no longer shows the dialog, reset it from Android Settings.
+
## Locations not syncing on mobile data
If **Wi-Fi Only Sync** is enabled, uploads are skipped while on cellular data. Locations continue to be recorded and queued locally - they sync automatically when you connect to Wi-Fi.
diff --git a/apps/docs/docs/integrations/custom-backend.md b/apps/docs/docs/integrations/custom-backend.md
index 220efde0..99783e64 100644
--- a/apps/docs/docs/integrations/custom-backend.md
+++ b/apps/docs/docs/integrations/custom-backend.md
@@ -15,7 +15,7 @@ Your server needs to:
- Handle `alt` and `bear` fields being absent (they are conditional)
- Handle up to 10 concurrent requests during batch sync
-HTTPS is required for public endpoints. HTTP is allowed for local addresses (`127.0.0.1`, `192.168.x.x`, `10.x.x.x`).
+HTTPS is required for public endpoints. HTTP is allowed for local addresses (`127.0.0.1`, `192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`). On Android 17+, connecting to local network addresses (not localhost) requires the Nearby Wi-Fi Devices permission, which Colota requests when you use **Test Connection**.
## Default Payload
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index e94ac9eb..7e104560 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -27,6 +27,10 @@
<!-- Network permission -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <!-- Local network access (required for local/private server endpoints) -->
+ <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
+ android:usesPermissionFlags="neverForLocation" />
+
<!-- Boot Receiver -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index 64c6800a..e0dedd10 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -133,6 +133,13 @@ class NetworkManager(private val context: Context) {
Log.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")
false
}
+ } catch (e: java.net.SocketException) {
+ if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {
+ Log.e(TAG, "Local network access denied - grant Nearby Devices permission", e)
+ } else {
+ Log.e(TAG, "Network error: ${e.message}", e)
+ }
+ false
} catch (e: Exception) {
Log.e(TAG, "Network error: ${e.message}", e)
false
@@ -161,6 +168,8 @@ class NetworkManager(private val context: Context) {
/**
* Checks if the given host is private or local.
+ * Matches Android's local network definition:
+ * loopback, site-local (RFC 1918), link-local, and CGNAT (100.64.0.0/10).
* Results are cached to avoid repeated DNS lookups on every request.
*/
private fun isPrivateHost(host: String): Boolean {
@@ -168,13 +177,26 @@ class NetworkManager(private val context: Context) {
return privateHostCache.getOrPut(host) {
try {
val address = java.net.InetAddress.getByName(host)
- address.isAnyLocalAddress || address.isLoopbackAddress || address.isSiteLocalAddress
+ address.isAnyLocalAddress ||
+ address.isLoopbackAddress ||
+ address.isSiteLocalAddress ||
+ address.isLinkLocalAddress ||
+ isCgnatAddress(address)
} catch (e: Exception) {
false
}
}
}
+ /** Checks if the address falls in the CGNAT range 100.64.0.0/10. */
+ private fun isCgnatAddress(address: java.net.InetAddress): Boolean {
+ val bytes = address.address
+ if (bytes.size != 4) return false
+ val a = bytes[0].toInt() and 0xFF
+ val b = bytes[1].toInt() and 0xFF
+ return a == 100 && b in 64..127
+ }
+
/**
* Masks the value of sensitive headers before logging.
* Shows the first 4 characters followed by "***", or the full value
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index 5b4996f5..a7d28aec 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -9,6 +9,7 @@ import { CheckCircle, ChevronRight } from "lucide-react-native"
import { Settings, ThemeColors } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
import { isPrivateHost, isEndpointAllowed } from "../../../utils/settingsValidation"
+import { ensureLocalNetworkPermission } from "../../../services/LocationServicePermission"
import { fonts } from "../../../styles/typography"
import { useTimeout } from "../../../hooks/useTimeout"
import { CONNECTION_TEST_TIMEOUT, TEST_RESULT_DISPLAY_MS } from "../../../constants"
@@ -52,7 +53,7 @@ export function ConnectionSettings({
try {
const recentLocation = await NativeLocationService.getMostRecentLocation()
if (!recentLocation) {
- setTestResponse("No location data yet — Start tracking to collect a test point, then try again.")
+ setTestResponse("No location data yet. Start tracking to collect a test point, then try again.")
setTestError(true)
return
}
@@ -78,6 +79,15 @@ export function ConnectionSettings({
if (fieldMap.bear) payload[fieldMap.bear] = recentLocation.bearing ?? 0
if (fieldMap.tst) payload[fieldMap.tst] = Math.floor(Date.now() / 1000)
+ if (isPrivateHost(endpointInput)) {
+ const granted = await ensureLocalNetworkPermission()
+ if (!granted) {
+ setTestResponse("Local network permission required to reach this server")
+ setTestError(true)
+ return
+ }
+ }
+
let authHeaders: Record<string, string> = {}
try {
authHeaders = await NativeLocationService.getAuthHeaders()
@@ -194,7 +204,7 @@ export function ConnectionSettings({
{!endpointInput && (
<Text style={[styles.endpointHint, { color: colors.warning }]}>
- No server configured — locations are saved locally
+ No server configured. Locations are saved locally
</Text>
)}
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 83787b4a..5954bca9 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -23,6 +23,7 @@ export { FloatingSaveIndicator } from "./ui/FloatingSaveIndicator"
export { Footer } from "./ui/Footer"
export { SpinningLoader } from "./ui/SpinningLoader"
export { LocationDisclosureModal } from "./ui/LocationDisclosureModal"
+export { LocalNetworkDisclosureModal } from "./ui/LocalNetworkDisclosureModal"
export { AppModal } from "./ui/AppModal"
export { ChipGroup } from "./ui/ChipGroup"
diff --git a/apps/mobile/src/components/ui/DisclosureModal.tsx b/apps/mobile/src/components/ui/DisclosureModal.tsx
new file mode 100644
index 00000000..6a6159ac
--- /dev/null
+++ b/apps/mobile/src/components/ui/DisclosureModal.tsx
@@ -0,0 +1,167 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useRef, useEffect, useCallback } from "react"
+import { Modal, View, Text, Pressable, StyleSheet, BackHandler } from "react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fonts } from "../../styles/typography"
+import { fontSizes } from "@colota/shared"
+
+interface DisclosureModalProps {
+ icon: React.ReactNode
+ title: string
+ paragraphs: string[]
+ confirmLabel: string
+ registerCallback: (cb: () => Promise<boolean>) => void
+}
+
+/**
+ * Reusable themed disclosure modal.
+ *
+ * Renders a centered card with an icon, title, body paragraphs,
+ * and "Not Now" / confirm buttons. The caller registers a callback
+ * that, when invoked, shows the modal and resolves with the user's choice.
+ */
+export function DisclosureModal({ icon, title, paragraphs, confirmLabel, registerCallback }: DisclosureModalProps) {
+ const { colors } = useTheme()
+ const [visible, setVisible] = useState(false)
+ const resolveRef = useRef<((value: boolean) => void) | null>(null)
+
+ useEffect(() => {
+ registerCallback(() => {
+ return new Promise<boolean>((resolve) => {
+ resolveRef.current = resolve
+ setVisible(true)
+ })
+ })
+ }, [registerCallback])
+
+ // Block hardware back button while visible
+ useEffect(() => {
+ if (!visible) return
+ const handler = BackHandler.addEventListener("hardwareBackPress", () => true)
+ return () => handler.remove()
+ }, [visible])
+
+ const handleConfirm = useCallback(() => {
+ setVisible(false)
+ resolveRef.current?.(true)
+ resolveRef.current = null
+ }, [])
+
+ const handleNotNow = useCallback(() => {
+ setVisible(false)
+ resolveRef.current?.(false)
+ resolveRef.current = null
+ }, [])
+
+ return (
+ <Modal visible={visible} transparent animationType="fade" statusBarTranslucent>
+ <View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
+ <View style={[styles.card, { backgroundColor: colors.cardElevated, borderRadius: colors.borderRadius + 4 }]}>
+ {/* Icon */}
+ <View style={[styles.iconContainer, { backgroundColor: colors.primary + "15" }]}>{icon}</View>
+
+ {/* Title */}
+ <Text style={[styles.title, { color: colors.text }]}>{title}</Text>
+
+ {/* Body */}
+ {paragraphs.map((text, i) => (
+ <Text key={i} style={[styles.body, i > 0 && styles.bodySpaced, { color: colors.textSecondary }]}>
+ {text}
+ </Text>
+ ))}
+
+ {/* Buttons */}
+ <View style={styles.buttons}>
+ <Pressable
+ style={({ pressed }) => [
+ styles.button,
+ styles.secondaryButton,
+ { borderColor: colors.border },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={handleNotNow}
+ >
+ <Text style={[styles.buttonText, { color: colors.textSecondary }]}>Not Now</Text>
+ </Pressable>
+
+ <Pressable
+ style={({ pressed }) => [
+ styles.button,
+ styles.primaryButton,
+ { backgroundColor: colors.primary },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={handleConfirm}
+ >
+ <Text style={[styles.buttonText, { color: colors.textOnPrimary }]}>{confirmLabel}</Text>
+ </Pressable>
+ </View>
+ </View>
+ </View>
+ </Modal>
+ )
+}
+
+const styles = StyleSheet.create({
+ overlay: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center",
+ paddingHorizontal: 32
+ },
+ card: {
+ width: "100%",
+ padding: 24,
+ elevation: 8,
+ shadowColor: "#000",
+ shadowOffset: { width: 0, height: 4 },
+ shadowOpacity: 0.2,
+ shadowRadius: 12
+ },
+ iconContainer: {
+ width: 56,
+ height: 56,
+ borderRadius: 28,
+ justifyContent: "center",
+ alignItems: "center",
+ alignSelf: "center",
+ marginBottom: 16
+ },
+ title: {
+ fontSize: fontSizes.cardTitle,
+ ...fonts.bold,
+ textAlign: "center",
+ marginBottom: 16
+ },
+ body: {
+ fontSize: fontSizes.body,
+ ...fonts.regular,
+ lineHeight: 20
+ },
+ bodySpaced: {
+ marginTop: 8
+ },
+ buttons: {
+ flexDirection: "row",
+ gap: 12,
+ marginTop: 24
+ },
+ button: {
+ flex: 1,
+ paddingVertical: 14,
+ borderRadius: 8,
+ alignItems: "center"
+ },
+ primaryButton: {},
+ secondaryButton: {
+ borderWidth: 1.5
+ },
+ buttonText: {
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
+ }
+})
diff --git a/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx b/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx
new file mode 100644
index 00000000..b8e4b588
--- /dev/null
+++ b/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx
@@ -0,0 +1,31 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Wifi } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { registerLocalNetworkDisclosureCallback } from "../../services/LocationServicePermission"
+import { DisclosureModal } from "./DisclosureModal"
+
+/**
+ * Disclosure modal for the local network (Nearby Devices) permission.
+ * Shown before requesting NEARBY_WIFI_DEVICES on Android 17+.
+ */
+export function LocalNetworkDisclosureModal() {
+ const { colors } = useTheme()
+
+ return (
+ <DisclosureModal
+ icon={<Wifi size={28} color={colors.primary} />}
+ title="Local Network Access"
+ paragraphs={[
+ "Your server is on the local network. Colota needs the nearby devices permission to reach it.",
+ "This permission is only used to connect to your self-hosted server. No device scanning or discovery is performed."
+ ]}
+ confirmLabel="Continue"
+ registerCallback={registerLocalNetworkDisclosureCallback}
+ />
+ )
+}
diff --git a/apps/mobile/src/components/ui/LocationDisclosureModal.tsx b/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
index 1a6184c1..556ac4e1 100644
--- a/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
+++ b/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
@@ -3,168 +3,30 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useRef, useEffect, useCallback } from "react"
-import { Modal, View, Text, Pressable, StyleSheet, BackHandler } from "react-native"
-import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
-import { fontSizes } from "@colota/shared"
+import React from "react"
import { MapPin } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
import { registerDisclosureCallback } from "../../services/LocationServicePermission"
+import { DisclosureModal } from "./DisclosureModal"
/**
* Prominent in-app disclosure modal for location data collection.
* Required by Google Play's User Data policy.
- *
- * Uses the app's theme (not system AlertDialog) to avoid
- * looking like an Android system prompt.
*/
export function LocationDisclosureModal() {
const { colors } = useTheme()
- const [visible, setVisible] = useState(false)
- const resolveRef = useRef<((value: boolean) => void) | null>(null)
-
- useEffect(() => {
- registerDisclosureCallback(() => {
- return new Promise<boolean>((resolve) => {
- resolveRef.current = resolve
- setVisible(true)
- })
- })
- }, [])
-
- // Block hardware back button while visible
- useEffect(() => {
- if (!visible) return
- const handler = BackHandler.addEventListener("hardwareBackPress", () => true)
- return () => handler.remove()
- }, [visible])
-
- const handleAgree = useCallback(() => {
- setVisible(false)
- resolveRef.current?.(true)
- resolveRef.current = null
- }, [])
-
- const handleNotNow = useCallback(() => {
- setVisible(false)
- resolveRef.current?.(false)
- resolveRef.current = null
- }, [])
return (
- <Modal visible={visible} transparent animationType="fade" statusBarTranslucent>
- <View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
- <View style={[styles.card, { backgroundColor: colors.cardElevated, borderRadius: colors.borderRadius + 4 }]}>
- {/* Icon */}
- <View style={[styles.iconContainer, { backgroundColor: colors.primary + "15" }]}>
- <MapPin size={28} color={colors.primary} />
- </View>
-
- {/* Title */}
- <Text style={[styles.title, { color: colors.text }]}>Location Data Collection</Text>
-
- {/* Body */}
- <Text style={[styles.body, { color: colors.textSecondary }]}>
- Colota collects location data to enable GPS tracking and sending your position to your configured server,
- even when the app is closed or not in use.
- </Text>
-
- <Text style={[styles.body, styles.bodySpaced, { color: colors.textSecondary }]}>
- This data is sent only to the server you set up. No data is shared with third parties.
- </Text>
-
- <Text style={[styles.body, styles.bodySpaced, { color: colors.textSecondary }]}>
- The app also needs notification and battery permissions to keep tracking running reliably.
- </Text>
-
- {/* Buttons */}
- <View style={styles.buttons}>
- <Pressable
- style={({ pressed }) => [
- styles.button,
- styles.secondaryButton,
- { borderColor: colors.border },
- pressed && { opacity: 0.7 }
- ]}
- onPress={handleNotNow}
- >
- <Text style={[styles.buttonText, { color: colors.textSecondary }]}>Not Now</Text>
- </Pressable>
-
- <Pressable
- style={({ pressed }) => [
- styles.button,
- styles.primaryButton,
- { backgroundColor: colors.primary },
- pressed && { opacity: 0.7 }
- ]}
- onPress={handleAgree}
- >
- <Text style={[styles.buttonText, { color: colors.textOnPrimary }]}>Agree</Text>
- </Pressable>
- </View>
- </View>
- </View>
- </Modal>
+ <DisclosureModal
+ icon={<MapPin size={28} color={colors.primary} />}
+ title="Location Data Collection"
+ paragraphs={[
+ "Colota collects location data to enable GPS tracking and sending your position to your configured server, even when the app is closed or not in use.",
+ "This data is sent only to the server you set up. No data is shared with third parties.",
+ "The app also needs notification and battery permissions to keep tracking running reliably."
+ ]}
+ confirmLabel="Agree"
+ registerCallback={registerDisclosureCallback}
+ />
)
}
-
-const styles = StyleSheet.create({
- overlay: {
- flex: 1,
- justifyContent: "center",
- alignItems: "center",
- paddingHorizontal: 32
- },
- card: {
- width: "100%",
- padding: 24,
- elevation: 8,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.2,
- shadowRadius: 12
- },
- iconContainer: {
- width: 56,
- height: 56,
- borderRadius: 28,
- justifyContent: "center",
- alignItems: "center",
- alignSelf: "center",
- marginBottom: 16
- },
- title: {
- fontSize: fontSizes.cardTitle,
- ...fonts.bold,
- textAlign: "center",
- marginBottom: 16
- },
- body: {
- fontSize: fontSizes.body,
- ...fonts.regular,
- lineHeight: 20
- },
- bodySpaced: {
- marginTop: 8
- },
- buttons: {
- flexDirection: "row",
- gap: 12,
- marginTop: 24
- },
- button: {
- flex: 1,
- paddingVertical: 14,
- borderRadius: 8,
- alignItems: "center"
- },
- primaryButton: {},
- secondaryButton: {
- borderWidth: 1.5
- },
- buttonText: {
- fontSize: fontSizes.label,
- ...fonts.semiBold
- }
-})
diff --git a/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx b/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx
new file mode 100644
index 00000000..ee78c895
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx
@@ -0,0 +1,113 @@
+import React from "react"
+import { render, fireEvent, act } from "@testing-library/react-native"
+import { Text } from "react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ overlay: "rgba(0,0,0,0.5)",
+ cardElevated: "#fff",
+ borderRadius: 12,
+ primary: "#0d9488",
+ text: "#000",
+ textSecondary: "#666",
+ border: "#e5e7eb",
+ textOnPrimary: "#fff"
+ }
+ })
+}))
+
+import { DisclosureModal } from "../DisclosureModal"
+
+describe("DisclosureModal", () => {
+ let triggerModal = () => Promise.resolve(false)
+ const mockRegister = (cb) => {
+ triggerModal = cb
+ }
+
+ const defaultProps = {
+ icon: <Text>Icon</Text>,
+ title: "Test Title",
+ paragraphs: ["First paragraph.", "Second paragraph."],
+ confirmLabel: "Confirm",
+ registerCallback: mockRegister
+ }
+
+ it("is not visible initially", () => {
+ const { queryByText } = render(<DisclosureModal {...defaultProps} />)
+
+ expect(queryByText("Test Title")).toBeNull()
+ })
+
+ it("becomes visible when the registered callback is invoked", async () => {
+ const { getByText } = render(<DisclosureModal {...defaultProps} />)
+
+ let resultPromise: Promise<boolean>
+ await act(async () => {
+ resultPromise = triggerModal()
+ })
+
+ expect(getByText("Test Title")).toBeTruthy()
+ expect(getByText("First paragraph.")).toBeTruthy()
+ expect(getByText("Second paragraph.")).toBeTruthy()
+ expect(getByText("Confirm")).toBeTruthy()
+ expect(getByText("Not Now")).toBeTruthy()
+
+ // Clean up by dismissing
+ await act(async () => {
+ fireEvent.press(getByText("Not Now"))
+ })
+ expect(await resultPromise!).toBe(false)
+ })
+
+ it("resolves true when confirm is pressed", async () => {
+ const { getByText } = render(<DisclosureModal {...defaultProps} />)
+
+ let resultPromise: Promise<boolean>
+ await act(async () => {
+ resultPromise = triggerModal()
+ })
+
+ await act(async () => {
+ fireEvent.press(getByText("Confirm"))
+ })
+
+ expect(await resultPromise!).toBe(true)
+ })
+
+ it("resolves false when Not Now is pressed", async () => {
+ const { getByText } = render(<DisclosureModal {...defaultProps} />)
+
+ let resultPromise: Promise<boolean>
+ await act(async () => {
+ resultPromise = triggerModal()
+ })
+
+ await act(async () => {
+ fireEvent.press(getByText("Not Now"))
+ })
+
+ expect(await resultPromise!).toBe(false)
+ })
+
+ it("renders the custom confirm label", async () => {
+ const { getByText } = render(<DisclosureModal {...defaultProps} confirmLabel="Agree" />)
+
+ await act(async () => {
+ triggerModal()
+ })
+
+ expect(getByText("Agree")).toBeTruthy()
+ })
+
+ it("renders a single paragraph correctly", async () => {
+ const { getByText, queryByText } = render(<DisclosureModal {...defaultProps} paragraphs={["Only paragraph."]} />)
+
+ await act(async () => {
+ triggerModal()
+ })
+
+ expect(getByText("Only paragraph.")).toBeTruthy()
+ expect(queryByText("Second paragraph.")).toBeNull()
+ })
+})
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index b27d297d..a7ddb992 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -10,6 +10,7 @@ import { useLocationTracking } from "../hooks/useLocationTracking"
import NativeLocationService from "../services/NativeLocationService"
import SettingsService from "../services/SettingsService"
import { LocationDisclosureModal } from "../components/ui/LocationDisclosureModal"
+import { LocalNetworkDisclosureModal } from "../components/ui/LocalNetworkDisclosureModal"
import { AppModal } from "../components/ui/AppModal"
import { checkPermissions } from "../services/LocationServicePermission"
import { logger } from "../utils/logger"
@@ -171,7 +172,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
// Auto-reconnect UI if tracking was active
const isTrackingActive = allRaw.tracking_enabled === "true"
if (isTrackingActive) {
- // Verify permission is still granted — Android kills the process
+ // Verify permission is still granted. Android kills the process
// when permission is revoked, leaving tracking_enabled stale
const perms = await checkPermissions()
if (!perms.location) {
@@ -305,6 +306,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
<TrackingContext.Provider value={value}>
<CoordsContext.Provider value={coords}>
<LocationDisclosureModal />
+ <LocalNetworkDisclosureModal />
<AppModal />
{children}
</CoordsContext.Provider>
diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
index c63877fa..42c1d7df 100644
--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -21,6 +21,10 @@ jest.mock("../../components/ui/LocationDisclosureModal", () => ({
LocationDisclosureModal: () => null
}))
+jest.mock("../../components/ui/LocalNetworkDisclosureModal", () => ({
+ LocalNetworkDisclosureModal: () => null
+}))
+
jest.mock("../../components/ui/AppModal", () => ({
AppModal: () => null
}))
diff --git a/apps/mobile/src/services/LocationServicePermission.ts b/apps/mobile/src/services/LocationServicePermission.ts
index 91714132..122b6166 100644
--- a/apps/mobile/src/services/LocationServicePermission.ts
+++ b/apps/mobile/src/services/LocationServicePermission.ts
@@ -16,6 +16,7 @@ export interface PermissionStatus {
background: boolean
notifications: boolean
batteryOptimized: boolean
+ localNetwork: boolean
}
/** Android version for background location (Android 10) */
@@ -24,12 +25,16 @@ const ANDROID_10 = 29
/** Android version for notifications (Android 13) */
const ANDROID_13 = 33
+/** Android version for local network permission enforcement (expected Android 17) */
+const ANDROID_LOCAL_NETWORK = 37
+
/**
* Callback registered by LocationDisclosureModal to show the themed disclosure.
* Falls back to Alert.alert if no modal is registered (e.g. in tests).
*/
type DisclosureCallback = () => Promise<boolean>
let _disclosureCallback: DisclosureCallback | null = null
+let _localNetworkDisclosureCallback: DisclosureCallback | null = null
/**
* Registers the disclosure modal callback.
@@ -39,6 +44,14 @@ export function registerDisclosureCallback(cb: DisclosureCallback) {
_disclosureCallback = cb
}
+/**
+ * Registers the local network disclosure modal callback.
+ * Called by LocalNetworkDisclosureModal on mount.
+ */
+export function registerLocalNetworkDisclosureCallback(cb: DisclosureCallback) {
+ _localNetworkDisclosureCallback = cb
+}
+
/**
* Requests all necessary permissions for location tracking.
*
@@ -130,22 +143,25 @@ export async function checkPermissions(): Promise<PermissionStatus> {
location: true,
background: true,
notifications: true,
- batteryOptimized: true
+ batteryOptimized: true,
+ localNetwork: true
}
}
- const [location, background, notifications, batteryOptimized] = await Promise.all([
+ const [location, background, notifications, batteryOptimized, localNetwork] = await Promise.all([
checkFineLocation(),
checkBackgroundLocation(),
checkNotifications(),
- checkBatteryOptimization()
+ checkBatteryOptimization(),
+ checkLocalNetwork()
])
return {
location,
background,
notifications,
- batteryOptimized
+ batteryOptimized,
+ localNetwork
}
}
@@ -176,3 +192,53 @@ async function checkBatteryOptimization(): Promise<boolean> {
return false
}
}
+
+async function checkLocalNetwork(): Promise<boolean> {
+ if (getAndroidVersion() < ANDROID_LOCAL_NETWORK) return true
+ return await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.NEARBY_WIFI_DEVICES)
+}
+
+/**
+ * Requests the local network permission for accessing private/local IP endpoints.
+ * Only needed on Android 16+ and only when the sync endpoint is a local address.
+ *
+ * @returns True if permission is granted (or not needed)
+ */
+export async function ensureLocalNetworkPermission(): Promise<boolean> {
+ if (Platform.OS !== "android") return true
+ if (getAndroidVersion() < ANDROID_LOCAL_NETWORK) return true
+
+ try {
+ const granted = await checkLocalNetwork()
+ if (granted) return true
+
+ // Show themed disclosure modal first
+ const consented = _localNetworkDisclosureCallback
+ ? await _localNetworkDisclosureCallback()
+ : await fallbackLocalNetworkDisclosure()
+ if (!consented) return false
+
+ const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.NEARBY_WIFI_DEVICES)
+ return result === PermissionsAndroid.RESULTS.GRANTED
+ } catch (err) {
+ logger.error("[PermissionService] Local network permission request failed:", err)
+ return false
+ }
+}
+
+/**
+ * Fallback disclosure using Alert (for tests or if modal not mounted).
+ */
+function fallbackLocalNetworkDisclosure(): Promise<boolean> {
+ return new Promise((resolve) => {
+ Alert.alert(
+ "Local Network Access",
+ "Your server is on the local network. Colota needs the nearby devices permission to reach it.",
+ [
+ { text: "Not Now", style: "cancel", onPress: () => resolve(false) },
+ { text: "Continue", onPress: () => resolve(true) }
+ ],
+ { cancelable: false }
+ )
+ })
+}
diff --git a/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts b/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
index e737b15b..7c4e3cb3 100644
--- a/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
+++ b/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
@@ -257,7 +257,8 @@ describe("checkPermissions", () => {
location: true,
background: true,
notifications: true,
- batteryOptimized: true
+ batteryOptimized: true,
+ localNetwork: true
})
})
diff --git a/apps/mobile/src/utils/settingsValidation.ts b/apps/mobile/src/utils/settingsValidation.ts
index 0353f10c..99175522 100644
--- a/apps/mobile/src/utils/settingsValidation.ts
+++ b/apps/mobile/src/utils/settingsValidation.ts
@@ -23,10 +23,12 @@ function isPrivateIP(host: string): boolean {
if (octets.some((o) => isNaN(o) || o < 0 || o > 255)) return false
const [a, b] = octets
return (
- (a === 127 && octets[1] === 0 && octets[2] === 0 && octets[3] === 1) ||
- a === 10 ||
- (a === 192 && b === 168) ||
- (a === 172 && b >= 16 && b <= 31)
+ a === 127 || // Loopback (127.0.0.0/8)
+ a === 10 || // RFC 1918 (10.0.0.0/8)
+ (a === 192 && b === 168) || // RFC 1918 (192.168.0.0/16)
+ (a === 172 && b >= 16 && b <= 31) || // RFC 1918 (172.16.0.0/12)
+ (a === 100 && b >= 64 && b <= 127) || // CGNAT (100.64.0.0/10)
+ (a === 169 && b === 254) // Link-local (169.254.0.0/16)
)
}