Skip to content

Colota - Android GPS Location tracker

feat(settings): share full setup as a colota://setup link (#468)

Max Dietrichdaa59b2b4ff8
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 332e4a4a..ee69a03a 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -305,6 +305,7 @@ For backups, two `internal` methods support the export/import flow without expos
| `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls |
| `BackupRestoreScreen` | Create or restore a password-encrypted `.colota` archive of all data, with strength meter and no-recovery confirmation |
| `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports |
+| `ShareSetupScreen` | Bundles selected config categories into a `colota://setup` link to share; credentials opt-in |
| `ActivityLogScreen` | In-app log viewer with level filtering, search, and export |
| `AboutScreen` | App version, device info, links to repository and privacy policy |
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.md
index 3340ff1d..3f721398 100644
--- a/apps/docs/docs/guides/deep-link-setup.md
+++ b/apps/docs/docs/guides/deep-link-setup.md
@@ -14,6 +14,14 @@ Fill in the settings you want to configure. Only the fields you set will be incl
<DeepLinkGenerator />
+## Sharing From the App
+
+You can also generate a setup link straight from an existing installation, without the browser generator. Open **Settings -> Share Setup**, tick which categories to include - Tracking, Sync, API, Geofences, Profiles and Credentials - and tap **Share** to send the `colota://setup` link through any app.
+
+Credentials are off by default. Enabling them puts your username, password, bearer token or custom headers into the link in plain text, so only share it over a trusted channel.
+
+Geofences and tracking profiles can also be shared on their own from the [Geofences](geofencing.md#sharing-zones) and Tracking Profiles screens.
+
## How It Works
1. User taps the link or scans a QR code
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 26ededa0..dea7ad55 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -68,6 +68,8 @@ When the recipient opens the link, Colota shows the import confirmation screen l
The share button is all-or-nothing - every zone in the list is included. The `id`, `createdAt` and `enabled` fields are stripped, so imported zones always start enabled and get fresh database entries on the recipient's device.
+To share zones together with your tracking, sync and API settings in a single link, use **Settings -> Share Setup** instead (see [Deep Link Setup](deep-link-setup.md#sharing-from-the-app)).
+
See the [Deep Link Setup](deep-link-setup.md#geofences) guide for the full payload format.
## How It Works
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 724b55ba..b276d353 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -4,7 +4,7 @@ title: Privacy Policy
# Privacy Policy
-**Last updated: May 25, 2026**
+**Last updated: June 14, 2026**
Colota ("the App") is a self-hosted GPS tracking application for Android, developed by Max Dietrich. This privacy policy explains what data the App collects, how it is used, and your rights regarding that data.
@@ -76,6 +76,8 @@ Restoring a backup overwrites the current database and credentials.
The App supports configuration via `colota://setup` deep links. These links can include server endpoints and authentication credentials. You must explicitly confirm before any configuration is applied. Only open setup links from sources you trust.
+You can also generate a setup link to share your own configuration (Settings -> Share Setup). Credentials are excluded by default; if you choose to include them they appear in the link in plain text, so only share it over a trusted channel.
+
## Data Transmission
The App **only transmits data to a server endpoint that you configure**. No data is sent anywhere by default.
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 062d52ba..27434346 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -31,6 +31,7 @@ import {
TrackingProfilesScreen,
ProfileEditorScreen,
SetupImportScreen,
+ ShareSetupScreen,
TripDetailScreen,
OfflineMapsScreen,
AppearanceScreen,
@@ -134,6 +135,11 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
component: SetupImportScreen,
title: "Import Configuration"
},
+ {
+ name: "Share Setup",
+ component: ShareSetupScreen,
+ title: "Share Setup"
+ },
{
name: "Trip Detail",
component: TripDetailScreen,
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 902dd989..ffc327e6 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -28,6 +28,7 @@ import { GeofenceLayers } from "../components/features/map/GeofenceLayers"
import { UserLocationOverlay } from "../components/features/map/UserLocationOverlay"
import { logger } from "../utils/logger"
import { formatShortDistance, shortDistanceUnit, inputToMeters } from "../utils/geo"
+import { buildGeofencesLink } from "../utils/setupLink"
const GeofenceMap = React.memo(function GeofenceMap({
tracking,
@@ -232,10 +233,7 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
const handleShareGeofences = useCallback(async () => {
if (geofences.length === 0) return
try {
- const exportable = geofences.map(({ id: _id, createdAt: _createdAt, enabled: _enabled, ...rest }) => rest)
- const encoded = btoa(JSON.stringify({ geofences: exportable }))
- const link = `colota://setup?config=${encoded}`
- await Share.share({ message: link })
+ await Share.share({ message: buildGeofencesLink(geofences) })
} catch (err) {
logger.error("[GeofenceScreen] Failed to share geofences:", err)
showAlert("Error", "Failed to share geofences.", "error")
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 845e68eb..520b3f5c 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -26,7 +26,8 @@ import {
ShieldCheck,
Info,
Heart,
- Clock
+ Clock,
+ Share2
} from "lucide-react-native"
import { logger } from "../utils/logger"
@@ -208,6 +209,14 @@ export function SettingsScreen({ navigation }: Props) {
onPress={() => navigation.navigate("Backup & Restore")}
/>
<Divider />
+ <ListItem
+ testID="nav-share-setup"
+ icon={Share2}
+ label="Share Setup"
+ sub="Share your settings, geofences and profiles as a link"
+ onPress={() => navigation.navigate("Share Setup")}
+ />
+ <Divider />
<ListItem
testID="nav-offline-maps"
icon={Map}
diff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsx
index 856cee9c..8873cf52 100644
--- a/apps/mobile/src/screens/SetupImportScreen.tsx
+++ b/apps/mobile/src/screens/SetupImportScreen.tsx
@@ -11,391 +11,12 @@ import { Container, Card, Button, SectionTitle } from "../components"
import { fonts } from "../styles/typography"
import { CircleAlert, CircleCheck, Import } from "lucide-react-native"
import SettingsService from "../services/SettingsService"
-import { OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX, defaultProfileDelays } from "../constants"
-import { isEndpointAllowed } from "../utils/settingsValidation"
import NativeLocationService from "../services/NativeLocationService"
import { showAlert } from "../services/modalService"
import { logger } from "../utils/logger"
-import {
- TRACKING_PRESETS,
- type Settings,
- type AuthConfig,
- type AuthType,
- type FieldMap,
- type CustomField,
- type ApiTemplateName,
- type HttpMethod,
- type DawarichMode,
- type SelectablePreset,
- type SyncPreset,
- type Geofence,
- type TrackingProfile,
- type ProfileConditionType
-} from "../types/global"
-
-type ImportGeofence = Omit<Geofence, "id" | "createdAt">
-type ImportProfile = Omit<TrackingProfile, "id" | "createdAt">
-
-// ============================================================================
-// TYPES
-// ============================================================================
-
-interface ParsedConfig {
- settings: Partial<Settings>
- auth: Partial<AuthConfig> | null
- geofences: ImportGeofence[]
- profiles: ImportProfile[]
-}
-
-interface ConfigEntry {
- label: string
- value: string
- category: "tracking" | "api" | "auth" | "geofence" | "profile"
- rejected?: boolean
-}
-
-interface ValidationResult {
- valid: boolean
- config: ParsedConfig
- entries: ConfigEntry[]
- error?: string
-}
-
-// ============================================================================
-// VALIDATION
-// ============================================================================
-
-const VALID_API_TEMPLATES: ApiTemplateName[] = [
- "custom",
- "dawarich",
- "geopulse",
- "overland",
- "owntracks",
- "phonetrack",
- "reitti",
- "traccar"
-]
-const VALID_HTTP_METHODS: HttpMethod[] = ["POST", "GET"]
-const VALID_DAWARICH_MODES: DawarichMode[] = ["single", "batch"]
-const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]
-
-const VALID_PROFILE_CONDITIONS: ProfileConditionType[] = [
- "charging",
- "android_auto",
- "speed_above",
- "speed_below",
- "stationary"
-]
-
-function detectPreset(settings: Partial<Settings>): SyncPreset {
- for (const [name, config] of Object.entries(TRACKING_PRESETS)) {
- if (
- settings.interval === config.interval &&
- settings.distance === config.distance &&
- settings.syncInterval === config.syncInterval &&
- settings.retryInterval === config.retryInterval
- ) {
- return name as SelectablePreset
- }
- }
- return "custom"
-}
-
-function validateConfig(raw: unknown): ValidationResult {
- if (!raw || typeof raw !== "object") {
- return {
- valid: false,
- config: { settings: {}, auth: null, geofences: [], profiles: [] },
- entries: [],
- error: "Invalid configuration format"
- }
- }
-
- const obj = raw as Record<string, unknown>
- const settings: Partial<Settings> = {}
- const entries: ConfigEntry[] = []
- let auth: Partial<AuthConfig> | null = null
-
- // --- API settings (endpoint) ---
-
- if ("endpoint" in obj && typeof obj.endpoint === "string" && obj.endpoint.length > 0) {
- if (isEndpointAllowed(obj.endpoint)) {
- settings.endpoint = obj.endpoint
- entries.push({ label: "Endpoint", value: obj.endpoint, category: "api" })
- } else {
- entries.push({ label: "Endpoint", value: "HTTP not allowed for public hosts", category: "api", rejected: true })
- }
- }
-
- // --- Tracking settings ---
-
- if ("interval" in obj && typeof obj.interval === "number" && obj.interval > 0) {
- settings.interval = obj.interval
- entries.push({ label: "Interval", value: `${obj.interval}s`, category: "tracking" })
- }
-
- if ("distance" in obj && typeof obj.distance === "number" && obj.distance >= 0) {
- settings.distance = obj.distance
- entries.push({ label: "Distance threshold", value: `${obj.distance}m`, category: "tracking" })
- }
-
- if ("syncInterval" in obj && typeof obj.syncInterval === "number" && obj.syncInterval >= 0) {
- settings.syncInterval = obj.syncInterval
- entries.push({
- label: "Sync interval",
- value: obj.syncInterval === 0 ? "Instant" : `${obj.syncInterval}s`,
- category: "tracking"
- })
- }
-
- if ("retryInterval" in obj && typeof obj.retryInterval === "number" && obj.retryInterval >= 0) {
- settings.retryInterval = obj.retryInterval
- entries.push({ label: "Retry interval", value: `${obj.retryInterval}s`, category: "tracking" })
- }
-
- if ("accuracyThreshold" in obj && typeof obj.accuracyThreshold === "number" && obj.accuracyThreshold > 0) {
- settings.accuracyThreshold = obj.accuracyThreshold
- entries.push({ label: "Accuracy threshold", value: `${obj.accuracyThreshold}m`, category: "tracking" })
- }
-
- if ("filterInaccurateLocations" in obj && typeof obj.filterInaccurateLocations === "boolean") {
- settings.filterInaccurateLocations = obj.filterInaccurateLocations
- entries.push({
- label: "Filter inaccurate",
- value: obj.filterInaccurateLocations ? "Yes" : "No",
- category: "tracking"
- })
- }
-
- if ("isOfflineMode" in obj && typeof obj.isOfflineMode === "boolean") {
- settings.isOfflineMode = obj.isOfflineMode
- entries.push({ label: "Offline mode", value: obj.isOfflineMode ? "Yes" : "No", category: "tracking" })
- }
-
- if ("syncCondition" in obj && typeof obj.syncCondition === "string") {
- settings.syncCondition = obj.syncCondition as any
- entries.push({ label: "Sync condition", value: obj.syncCondition, category: "tracking" })
- }
-
- if ("syncSsid" in obj && typeof obj.syncSsid === "string") {
- settings.syncSsid = obj.syncSsid
- entries.push({ label: "Sync SSID", value: obj.syncSsid, category: "tracking" })
- }
-
- // --- API settings ---
-
- if (
- "apiTemplate" in obj &&
- typeof obj.apiTemplate === "string" &&
- VALID_API_TEMPLATES.includes(obj.apiTemplate as ApiTemplateName)
- ) {
- settings.apiTemplate = obj.apiTemplate as ApiTemplateName
- entries.push({ label: "API template", value: obj.apiTemplate, category: "api" })
- }
-
- if (
- "httpMethod" in obj &&
- typeof obj.httpMethod === "string" &&
- VALID_HTTP_METHODS.includes(obj.httpMethod as HttpMethod)
- ) {
- settings.httpMethod = obj.httpMethod as HttpMethod
- entries.push({ label: "HTTP method", value: obj.httpMethod, category: "api" })
- }
-
- if (
- "dawarichMode" in obj &&
- typeof obj.dawarichMode === "string" &&
- VALID_DAWARICH_MODES.includes(obj.dawarichMode as DawarichMode)
- ) {
- settings.dawarichMode = obj.dawarichMode as DawarichMode
- entries.push({ label: "Dawarich mode", value: obj.dawarichMode, category: "api" })
- }
-
- if (
- "overlandBatchSize" in obj &&
- typeof obj.overlandBatchSize === "number" &&
- obj.overlandBatchSize >= OVERLAND_BATCH_MIN &&
- obj.overlandBatchSize <= OVERLAND_BATCH_MAX
- ) {
- settings.overlandBatchSize = Math.floor(obj.overlandBatchSize)
- entries.push({ label: "Overland batch size", value: String(settings.overlandBatchSize), category: "api" })
- }
-
- if ("fieldMap" in obj && typeof obj.fieldMap === "object" && obj.fieldMap !== null) {
- const fm = obj.fieldMap as Record<string, unknown>
- const validFieldMap: Partial<FieldMap> = {}
- let hasValid = false
- for (const [key, val] of Object.entries(fm)) {
- if (typeof val === "string") {
- ;(validFieldMap as any)[key] = val
- hasValid = true
- }
- }
- if (hasValid) {
- settings.fieldMap = validFieldMap as FieldMap
- entries.push({ label: "Field mapping", value: `${Object.keys(validFieldMap).length} fields`, category: "api" })
- }
- }
-
- if ("customFields" in obj && Array.isArray(obj.customFields)) {
- const validFields: CustomField[] = obj.customFields.filter(
- (f: any) => f && typeof f.key === "string" && typeof f.value === "string" && f.key.length > 0
- )
- if (validFields.length > 0) {
- settings.customFields = validFields
- entries.push({ label: "Custom fields", value: `${validFields.length} fields`, category: "api" })
- }
- }
-
- // --- Auth settings ---
-
- if ("auth" in obj && typeof obj.auth === "object" && obj.auth !== null) {
- const authObj = obj.auth as Record<string, unknown>
- auth = {}
-
- if ("type" in authObj && typeof authObj.type === "string" && VALID_AUTH_TYPES.includes(authObj.type as AuthType)) {
- auth.authType = authObj.type as AuthType
- entries.push({ label: "Auth type", value: authObj.type, category: "auth" })
- }
-
- if ("username" in authObj && typeof authObj.username === "string" && authObj.username.length > 0) {
- auth.username = authObj.username
- entries.push({ label: "Username", value: authObj.username, category: "auth" })
- }
-
- if ("password" in authObj && typeof authObj.password === "string" && authObj.password.length > 0) {
- auth.password = authObj.password
- entries.push({ label: "Password", value: "\u2022".repeat(8), category: "auth" })
- }
-
- if ("bearerToken" in authObj && typeof authObj.bearerToken === "string" && authObj.bearerToken.length > 0) {
- auth.bearerToken = authObj.bearerToken
- const masked =
- authObj.bearerToken.length > 8
- ? authObj.bearerToken.slice(0, 4) + "\u2022".repeat(4) + authObj.bearerToken.slice(-4)
- : "\u2022".repeat(authObj.bearerToken.length)
- entries.push({ label: "Bearer token", value: masked, category: "auth" })
- }
-
- if (Object.keys(auth).length === 0) auth = null
- }
-
- if ("customHeaders" in obj && typeof obj.customHeaders === "object" && obj.customHeaders !== null) {
- const headers = obj.customHeaders as Record<string, unknown>
- const validHeaders: Record<string, string> = {}
- for (const [key, val] of Object.entries(headers)) {
- if (typeof val === "string") {
- validHeaders[key] = val
- }
- }
- if (Object.keys(validHeaders).length > 0) {
- if (!auth) auth = {}
- auth.customHeaders = validHeaders
- entries.push({ label: "Custom headers", value: `${Object.keys(validHeaders).length} headers`, category: "auth" })
- }
- }
-
- // --- Geofences ---
-
- const geofences: ImportGeofence[] = []
-
- if ("geofences" in obj && Array.isArray(obj.geofences)) {
- for (const entry of obj.geofences) {
- if (!entry || typeof entry !== "object") continue
- const g = entry as Record<string, unknown>
- if (
- typeof g.name !== "string" ||
- g.name.length === 0 ||
- typeof g.lat !== "number" ||
- typeof g.lon !== "number" ||
- typeof g.radius !== "number" ||
- g.radius <= 0
- ) {
- continue
- }
- geofences.push({
- name: g.name,
- lat: g.lat,
- lon: g.lon,
- radius: g.radius,
- enabled: typeof g.enabled === "boolean" ? g.enabled : true,
- pauseTracking: typeof g.pauseTracking === "boolean" ? g.pauseTracking : false,
- pauseOnWifi: typeof g.pauseOnWifi === "boolean" ? g.pauseOnWifi : false,
- pauseOnMotionless: typeof g.pauseOnMotionless === "boolean" ? g.pauseOnMotionless : false,
- motionlessTimeoutMinutes: typeof g.motionlessTimeoutMinutes === "number" ? g.motionlessTimeoutMinutes : 10,
- heartbeatEnabled: typeof g.heartbeatEnabled === "boolean" ? g.heartbeatEnabled : false,
- heartbeatIntervalMinutes: typeof g.heartbeatIntervalMinutes === "number" ? g.heartbeatIntervalMinutes : 15
- })
- entries.push({ label: g.name, value: `${g.radius}m`, category: "geofence" })
- }
- }
-
- // --- Tracking Profiles ---
-
- const profiles: ImportProfile[] = []
-
- if ("profiles" in obj && Array.isArray(obj.profiles)) {
- for (const entry of obj.profiles) {
- if (!entry || typeof entry !== "object") continue
- const p = entry as Record<string, unknown>
- if (
- typeof p.name !== "string" ||
- p.name.length === 0 ||
- typeof p.interval !== "number" ||
- p.interval < 1 ||
- typeof p.distance !== "number" ||
- p.distance < 0 ||
- typeof p.syncInterval !== "number" ||
- p.syncInterval < 0
- ) {
- continue
- }
-
- const condRaw = p.condition as Record<string, unknown> | undefined
- if (!condRaw || typeof condRaw !== "object" || typeof condRaw.type !== "string") continue
- if (!VALID_PROFILE_CONDITIONS.includes(condRaw.type as ProfileConditionType)) continue
- const condType = condRaw.type as ProfileConditionType
- const needsSpeed = condType === "speed_above" || condType === "speed_below"
- if (needsSpeed && (typeof condRaw.speedThreshold !== "number" || condRaw.speedThreshold <= 0)) continue
- const condition: TrackingProfile["condition"] = needsSpeed
- ? { type: condType, speedThreshold: condRaw.speedThreshold as number }
- : { type: condType }
-
- const delays = defaultProfileDelays(condType)
- profiles.push({
- name: p.name,
- interval: p.interval,
- distance: p.distance,
- syncInterval: p.syncInterval,
- priority: typeof p.priority === "number" ? p.priority : 10,
- activationDelay:
- typeof p.activationDelay === "number" && p.activationDelay >= 0 ? p.activationDelay : delays.activationDelay,
- deactivationDelay:
- typeof p.deactivationDelay === "number" && p.deactivationDelay >= 0
- ? p.deactivationDelay
- : delays.deactivationDelay,
- enabled: typeof p.enabled === "boolean" ? p.enabled : true,
- condition
- })
- entries.push({ label: p.name, value: `${p.interval}s`, category: "profile" })
- }
- }
-
- if (entries.length === 0) {
- return {
- valid: false,
- config: { settings, auth, geofences, profiles },
- entries,
- error: "No valid settings found in configuration"
- }
- }
-
- return { valid: true, config: { settings, auth, geofences, profiles }, entries }
-}
-
-// ============================================================================
-// SCREEN
-// ============================================================================
+import { type Settings } from "../types/global"
+import { validateConfig, detectPreset, type ConfigEntry, type ValidationResult } from "../utils/setupConfig"
+import { decodeConfig } from "../utils/setupLink"
export function SetupImportScreen({ route, navigation }: any) {
const { colors } = useTheme()
@@ -415,9 +36,7 @@ export function SetupImportScreen({ route, navigation }: any) {
} as ValidationResult
}
- const decoded = atob(configParam)
- const parsed = JSON.parse(decoded)
- return validateConfig(parsed)
+ return validateConfig(decodeConfig(configParam))
} catch (e) {
logger.error("[SetupImport] Failed to parse config:", e)
return {
@@ -620,10 +239,6 @@ export function SetupImportScreen({ route, navigation }: any) {
)
}
-// ============================================================================
-// STYLES
-// ============================================================================
-
const styles = StyleSheet.create({
content: {
padding: 16,
diff --git a/apps/mobile/src/screens/ShareSetupScreen.tsx b/apps/mobile/src/screens/ShareSetupScreen.tsx
new file mode 100644
index 00000000..302a69a4
--- /dev/null
+++ b/apps/mobile/src/screens/ShareSetupScreen.tsx
@@ -0,0 +1,262 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback, useEffect, useMemo, useState } from "react"
+import { View, Text, ScrollView, StyleSheet, Switch, Share } from "react-native"
+import { useTheme } from "../hooks/useTheme"
+import { useTracking } from "../contexts/TrackingProvider"
+import { Container, Card, Button, SectionTitle } from "../components"
+import { fonts } from "../styles/typography"
+import { Share2, TriangleAlert } from "lucide-react-native"
+import NativeLocationService from "../services/NativeLocationService"
+import { showAlert } from "../services/modalService"
+import { logger } from "../utils/logger"
+import { buildSetupConfig, buildSetupLink, type SetupShareParts, type SetupShareSelection } from "../utils/setupLink"
+import { DEFAULT_AUTH_CONFIG, type AuthConfig, type Geofence, type TrackingProfile } from "../types/global"
+
+type ShareCategory = keyof SetupShareSelection
+
+export function ShareSetupScreen() {
+ const { colors } = useTheme()
+ const { settings } = useTracking()
+
+ const [auth, setAuth] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG)
+ const [geofences, setGeofences] = useState<Geofence[]>([])
+ const [profiles, setProfiles] = useState<TrackingProfile[]>([])
+
+ // Nothing selected by default - the user opts in.
+ const [selection, setSelection] = useState<SetupShareSelection>({
+ tracking: false,
+ sync: false,
+ api: false,
+ credentials: false,
+ geofences: false,
+ profiles: false
+ })
+
+ useEffect(() => {
+ let active = true
+ ;(async () => {
+ try {
+ const [a, g, p] = await Promise.all([
+ NativeLocationService.getAuthConfig(),
+ NativeLocationService.getGeofences(),
+ NativeLocationService.getProfiles()
+ ])
+ if (!active) return
+ setAuth(a)
+ setGeofences(g)
+ setProfiles(p)
+ } catch (err) {
+ logger.error("[ShareSetup] Failed to load config:", err)
+ }
+ })()
+ return () => {
+ active = false
+ }
+ }, [])
+
+ const parts: SetupShareParts = useMemo(
+ () => ({ settings, auth, geofences, profiles }),
+ [settings, auth, geofences, profiles]
+ )
+
+ const config = useMemo(() => buildSetupConfig(parts, selection), [parts, selection])
+ const isEmpty = Object.keys(config).length === 0
+
+ const hasCredentials = auth.authType !== "none" || Object.keys(auth.customHeaders).length > 0
+
+ // The sensitive fields the credentials toggle would put in the link.
+ const credentialFields = useMemo(() => {
+ const fields: string[] = []
+ if (auth.authType === "basic") {
+ if (auth.username) fields.push("username")
+ if (auth.password) fields.push("password")
+ } else if (auth.authType === "bearer") {
+ if (auth.bearerToken) fields.push("bearer token")
+ }
+ if (Object.keys(auth.customHeaders).length > 0) fields.push("custom headers")
+ return fields
+ }, [auth])
+
+ const toggle = useCallback((key: ShareCategory) => {
+ setSelection((s) => ({ ...s, [key]: !s[key] }))
+ }, [])
+
+ const handleShare = useCallback(async () => {
+ if (isEmpty) return
+ try {
+ await Share.share({ message: buildSetupLink(parts, selection) })
+ } catch (err) {
+ logger.error("[ShareSetup] Failed to share setup:", err)
+ showAlert("Error", "Failed to share setup.", "error")
+ }
+ }, [parts, selection, isEmpty])
+
+ const rows: { key: ShareCategory; label: string; sub: string; disabled?: boolean }[] = [
+ { key: "tracking", label: "Tracking", sub: "GPS interval, distance and accuracy filter" },
+ { key: "sync", label: "Sync", sub: "Sync interval, conditions and offline mode" },
+ { key: "api", label: "API", sub: "Endpoint, template and field mapping" },
+ {
+ key: "geofences",
+ label: "Geofences",
+ sub: geofences.length > 0 ? `${geofences.length} zone${geofences.length === 1 ? "" : "s"}` : "None saved",
+ disabled: geofences.length === 0
+ },
+ {
+ key: "profiles",
+ label: "Tracking profiles",
+ sub: profiles.length > 0 ? `${profiles.length} profile${profiles.length === 1 ? "" : "s"}` : "None saved",
+ disabled: profiles.length === 0
+ },
+ {
+ key: "credentials",
+ label: "Credentials",
+ sub: hasCredentials ? "Authentication secrets - included only if checked" : "None configured",
+ disabled: !hasCredentials
+ }
+ ]
+
+ return (
+ <Container>
+ <ScrollView contentContainerStyle={styles.content}>
+ <Card style={styles.headerCard}>
+ <View style={styles.headerRow}>
+ <Share2 size={28} color={colors.primary} />
+ <View style={styles.headerText}>
+ <Text style={[styles.title, { color: colors.text }]}>Share Setup</Text>
+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>
+ Choose what to bundle into a setup link, then share it. The recipient opens it to apply the same
+ configuration.
+ </Text>
+ </View>
+ </View>
+ </Card>
+
+ <View style={styles.section}>
+ <SectionTitle>INCLUDE</SectionTitle>
+ <Card>
+ {rows.map((row, i) => (
+ <View
+ key={row.key}
+ style={[
+ styles.row,
+ i < rows.length - 1 && styles.rowBorder,
+ i < rows.length - 1 && { borderBottomColor: colors.border }
+ ]}
+ >
+ <View style={styles.rowText}>
+ <Text style={[styles.rowLabel, { color: row.disabled ? colors.textSecondary : colors.text }]}>
+ {row.label}
+ </Text>
+ <Text style={[styles.rowSub, { color: colors.textSecondary }]}>{row.sub}</Text>
+ </View>
+ <Switch
+ testID={`share-${row.key}`}
+ value={selection[row.key] && !row.disabled}
+ onValueChange={() => toggle(row.key)}
+ disabled={row.disabled}
+ />
+ </View>
+ ))}
+ </Card>
+ </View>
+
+ {selection.credentials && hasCredentials && credentialFields.length > 0 && (
+ <View style={styles.section}>
+ <Card style={[styles.warningCard, { borderColor: colors.error }]}>
+ <View style={styles.headerRow}>
+ <TriangleAlert size={20} color={colors.error} />
+ <Text style={[styles.warningText, { color: colors.text }]}>
+ This link will contain your {credentialFields.join(", ")} in plain text. Anyone who sees the link can
+ read them - only share it over a trusted channel.
+ </Text>
+ </View>
+ </Card>
+ </View>
+ )}
+
+ <View style={styles.actions}>
+ <Button title="Share" onPress={handleShare} variant="primary" icon={Share2} disabled={isEmpty} />
+ {isEmpty && (
+ <Text style={[styles.emptyHint, { color: colors.textSecondary }]}>
+ Select at least one category to share.
+ </Text>
+ )}
+ </View>
+ </ScrollView>
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ content: {
+ padding: 16,
+ paddingBottom: 40
+ },
+ headerCard: {
+ marginBottom: 16
+ },
+ headerRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12
+ },
+ headerText: {
+ flex: 1
+ },
+ title: {
+ fontSize: 18,
+ ...fonts.bold
+ },
+ subtitle: {
+ fontSize: 13,
+ ...fonts.regular,
+ marginTop: 2
+ },
+ section: {
+ marginTop: 8
+ },
+ row: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ paddingVertical: 12,
+ gap: 12
+ },
+ rowBorder: {
+ borderBottomWidth: StyleSheet.hairlineWidth
+ },
+ rowText: {
+ flex: 1
+ },
+ rowLabel: {
+ fontSize: 14,
+ ...fonts.semiBold
+ },
+ rowSub: {
+ fontSize: 12,
+ ...fonts.regular,
+ marginTop: 2
+ },
+ warningCard: {
+ borderWidth: StyleSheet.hairlineWidth
+ },
+ warningText: {
+ flex: 1,
+ fontSize: 12,
+ ...fonts.regular,
+ lineHeight: 17
+ },
+ actions: {
+ marginTop: 24
+ },
+ emptyHint: {
+ fontSize: 12,
+ ...fonts.regular,
+ textAlign: "center",
+ marginTop: 8
+ }
+})
diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
index 6979ca62..fff19589 100644
--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx
+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
@@ -14,6 +14,7 @@ import { fonts } from "../styles/typography"
import { Container, SectionTitle, Card } from "../components"
import { Plus, X, Zap, Share2 } from "lucide-react-native"
import { logger } from "../utils/logger"
+import { buildProfilesLink } from "../utils/setupLink"
import { PROFILE_CONDITIONS, MS_TO_KMH, HIT_SLOP_MD } from "../constants"
function formatCondition(profile: SavedTrackingProfile): string {
@@ -76,10 +77,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
const handleShareProfiles = useCallback(async () => {
if (profiles.length === 0) return
try {
- const exportable = profiles.map(({ id: _id, createdAt: _createdAt, ...rest }) => rest)
- const encoded = btoa(JSON.stringify({ profiles: exportable }))
- const link = `colota://setup?config=${encoded}`
- await Share.share({ message: link })
+ await Share.share({ message: buildProfilesLink(profiles) })
} catch (err) {
logger.error("[TrackingProfilesScreen] Failed to share profiles:", err)
showAlert("Error", "Failed to share profiles.", "error")
diff --git a/apps/mobile/src/screens/__tests__/ShareSetupScreen.test.tsx b/apps/mobile/src/screens/__tests__/ShareSetupScreen.test.tsx
new file mode 100644
index 00000000..8a92cfff
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/ShareSetupScreen.test.tsx
@@ -0,0 +1,157 @@
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { Share } from "react-native"
+
+jest.mock("@react-navigation/native", () => ({
+ useRoute: () => ({ name: "Share Setup", params: {} }),
+ useFocusEffect: jest.fn(),
+ useNavigation: () => ({ navigate: jest.fn() })
+}))
+
+jest.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
+ SafeAreaProvider: ({ children }: any) => children
+}))
+
+jest.mock("@maplibre/maplibre-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ __esModule: true,
+ Map: (props: any) => R.createElement(View, props),
+ Camera: () => null,
+ GeoJSONSource: ({ children }: any) => children,
+ Layer: () => null,
+ Marker: ({ children }: any) => children
+ }
+})
+
+jest.mock("../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ primary: "#0d9488",
+ primaryDark: "#0d9488",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textDisabled: "#d1d5db",
+ textOnPrimary: "#fff",
+ textLight: "#9ca3af",
+ card: "#fff",
+ surface: "#fff",
+ background: "#fff",
+ backgroundElevated: "#f9fafb",
+ border: "#e5e7eb",
+ borderRadius: 12,
+ success: "#22c55e",
+ warning: "#f59e0b",
+ info: "#3b82f6",
+ error: "#ef4444",
+ link: "#0d9488",
+ placeholder: "#d1d5db",
+ overlay: "rgba(0,0,0,0.5)"
+ },
+ mode: "light"
+ })
+}))
+
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: {
+ interval: 10,
+ distance: 5,
+ accuracyThreshold: 50,
+ filterInaccurateLocations: true,
+ syncInterval: 0,
+ retryInterval: 30,
+ isOfflineMode: false,
+ syncCondition: "any",
+ syncSsid: "",
+ endpoint: "https://example.com/api",
+ apiTemplate: "custom",
+ httpMethod: "POST",
+ dawarichMode: "single",
+ overlandBatchSize: 50,
+ fieldMap: {},
+ customFields: []
+ }
+ })
+}))
+
+const mockGetAuthConfig = jest.fn()
+const mockGetGeofences = jest.fn()
+const mockGetProfiles = jest.fn()
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ getAuthConfig: (...a: any[]) => mockGetAuthConfig(...a),
+ getGeofences: (...a: any[]) => mockGetGeofences(...a),
+ getProfiles: (...a: any[]) => mockGetProfiles(...a)
+ }
+}))
+
+jest.mock("../../services/modalService", () => ({ showAlert: jest.fn() }))
+
+import { ShareSetupScreen } from "../ShareSetupScreen"
+
+const NO_AUTH = { authType: "none", username: "", password: "", bearerToken: "", customHeaders: {} }
+const BASIC_AUTH = { authType: "basic", username: "user", password: "secret", bearerToken: "", customHeaders: {} }
+
+const decode = (link: string) => JSON.parse(atob(link.split("config=")[1]))
+
+describe("ShareSetupScreen", () => {
+ let shareSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockGetAuthConfig.mockResolvedValue(NO_AUTH)
+ mockGetGeofences.mockResolvedValue([])
+ mockGetProfiles.mockResolvedValue([])
+ shareSpy = jest.spyOn(Share, "share").mockResolvedValue({ action: "sharedAction" } as any)
+ })
+
+ afterEach(() => shareSpy.mockRestore())
+
+ it("shares nothing until a category is toggled on", async () => {
+ const { getByText } = render(<ShareSetupScreen />)
+ await waitFor(() => expect(mockGetAuthConfig).toHaveBeenCalled())
+
+ fireEvent.press(getByText("Share"))
+ expect(shareSpy).not.toHaveBeenCalled()
+ })
+
+ it("shares only the categories the user toggles on", async () => {
+ const { getByText, getByTestId } = render(<ShareSetupScreen />)
+ await waitFor(() => expect(mockGetAuthConfig).toHaveBeenCalled())
+
+ fireEvent(getByTestId("share-tracking"), "valueChange", true)
+ fireEvent.press(getByText("Share"))
+ await waitFor(() => expect(shareSpy).toHaveBeenCalledTimes(1))
+
+ const config = decode(shareSpy.mock.calls[0][0].message)
+ expect(config.interval).toBe(10)
+ expect(config.endpoint).toBeUndefined() // API not toggled on
+ expect(config.auth).toBeUndefined() // credentials not toggled on
+ })
+
+ it("disables the credentials toggle when none are configured", async () => {
+ const { getByTestId } = render(<ShareSetupScreen />)
+ await waitFor(() => expect(mockGetAuthConfig).toHaveBeenCalled())
+
+ const credentials = getByTestId("share-credentials")
+ expect(credentials.props.value).toBe(false)
+ expect(credentials.props.disabled).toBe(true)
+ })
+
+ it("includes credentials when configured and toggled on", async () => {
+ mockGetAuthConfig.mockResolvedValue(BASIC_AUTH)
+ const { getByTestId, getByText } = render(<ShareSetupScreen />)
+ await waitFor(() => expect(getByTestId("share-credentials").props.disabled).toBe(false))
+
+ fireEvent(getByTestId("share-credentials"), "valueChange", true)
+ fireEvent.press(getByText("Share"))
+ await waitFor(() => expect(shareSpy).toHaveBeenCalledTimes(1))
+
+ const config = decode(shareSpy.mock.calls[0][0].message)
+ expect(config.auth).toEqual({ type: "basic", username: "user", password: "secret" })
+ })
+})
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index eec195eb..4e833fad 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -24,6 +24,7 @@ export { AppearanceScreen } from "./AppearanceScreen"
export { ConnectionScreen } from "./ConnectionScreen"
export { TrackingSyncScreen } from "./TrackingSyncScreen"
export { SetupImportScreen } from "./SetupImportScreen"
+export { ShareSetupScreen } from "./ShareSetupScreen"
export { TripDetailScreen } from "./TripDetailScreen"
export { OfflineMapsScreen } from "./OfflineMapsScreen"
export { BackupRestoreScreen } from "./BackupRestoreScreen"
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index 03d57d21..9e64f1aa 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -29,6 +29,7 @@ export type RootStackParamList = {
"Profile Editor": { profileId?: number } | undefined
"About Colota": undefined
"Setup Import": undefined
+ "Share Setup": undefined
"Trip Detail": { trip: Trip; trips: Trip[] }
"Offline Maps": undefined
Logging: undefined
diff --git a/apps/mobile/src/utils/__tests__/setupLink.test.ts b/apps/mobile/src/utils/__tests__/setupLink.test.ts
new file mode 100644
index 00000000..94b39a73
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/setupLink.test.ts
@@ -0,0 +1,142 @@
+import {
+ buildSetupConfig,
+ buildSetupLink,
+ encodeConfig,
+ decodeConfig,
+ type SetupShareParts,
+ type SetupShareSelection
+} from "../setupLink"
+import { validateConfig } from "../setupConfig"
+import type { Settings, AuthConfig, Geofence, TrackingProfile } from "../../types/global"
+
+const settings = {
+ interval: 10,
+ distance: 5,
+ filterInaccurateLocations: true,
+ accuracyThreshold: 50,
+ endpoint: "https://example.com/api",
+ fieldMap: { lat: "latitude" },
+ customFields: [{ key: "device", value: "phone" }],
+ apiTemplate: "custom",
+ httpMethod: "POST",
+ dawarichMode: "single",
+ overlandBatchSize: 50,
+ syncInterval: 0,
+ retryInterval: 30,
+ isOfflineMode: false,
+ syncCondition: "any",
+ syncSsid: ""
+} as Settings
+
+const auth: AuthConfig = {
+ authType: "basic",
+ username: "user",
+ password: "secret",
+ bearerToken: "",
+ customHeaders: { "X-Api-Key": "abc" }
+}
+
+const geofences: Geofence[] = [
+ {
+ id: 1,
+ name: "Home",
+ lat: 52.52,
+ lon: 13.405,
+ radius: 100,
+ enabled: true,
+ pauseTracking: true,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15,
+ createdAt: 123
+ }
+]
+
+const profiles: TrackingProfile[] = [
+ {
+ id: 2,
+ name: "Driving",
+ interval: 5,
+ distance: 0,
+ syncInterval: 0,
+ priority: 10,
+ condition: { type: "speed_above", speedThreshold: 8.33 },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true,
+ createdAt: 456
+ }
+]
+
+const parts: SetupShareParts = { settings, auth, geofences, profiles }
+const ALL: SetupShareSelection = {
+ tracking: true,
+ sync: true,
+ api: true,
+ credentials: true,
+ geofences: true,
+ profiles: true
+}
+
+describe("setupLink", () => {
+ it("produces a config the importer accepts, round-tripping every category", () => {
+ const result = validateConfig(buildSetupConfig(parts, ALL))
+
+ expect(result.valid).toBe(true)
+ // tracking + sync + api
+ expect(result.config.settings.interval).toBe(10)
+ expect(result.config.settings.accuracyThreshold).toBe(50)
+ expect(result.config.settings.syncInterval).toBe(0)
+ expect(result.config.settings.endpoint).toBe("https://example.com/api")
+ expect(result.config.settings.apiTemplate).toBe("custom")
+ expect(result.config.settings.fieldMap).toEqual({ lat: "latitude" })
+ // credentials map authType -> type and keep secrets + headers
+ expect(result.config.auth?.authType).toBe("basic")
+ expect(result.config.auth?.password).toBe("secret")
+ expect(result.config.auth?.customHeaders).toEqual({ "X-Api-Key": "abc" })
+ // collections, with DB-only fields stripped
+ expect(result.config.geofences).toHaveLength(1)
+ expect(result.config.geofences[0].name).toBe("Home")
+ expect(result.config.profiles).toHaveLength(1)
+ expect(result.config.profiles[0].condition).toEqual({ type: "speed_above", speedThreshold: 8.33 })
+ })
+
+ it("omits credentials entirely when that category is unchecked", () => {
+ const config = buildSetupConfig(parts, { ...ALL, credentials: false })
+
+ expect(config.auth).toBeUndefined()
+ expect(config.customHeaders).toBeUndefined()
+ expect(validateConfig(config).config.auth).toBeNull()
+ })
+
+ it("includes only the selected category", () => {
+ const config = buildSetupConfig(parts, {
+ tracking: false,
+ sync: false,
+ api: false,
+ credentials: false,
+ geofences: true,
+ profiles: false
+ })
+
+ expect(Object.keys(config)).toEqual(["geofences"])
+ expect(validateConfig(config).valid).toBe(true)
+ })
+
+ it("builds a colota://setup link the importer can decode", () => {
+ const link = buildSetupLink(parts, ALL)
+ expect(link).toMatch(/^colota:\/\/setup\?config=/)
+ expect(validateConfig(decodeConfig(link.split("config=")[1])).valid).toBe(true)
+ })
+
+ it("decodeConfig restores a '+' that the deep-link query parser turned into a space", () => {
+ // The high-byte run guarantees a '+' in the base64 - the char the query parser mangles to a space.
+ const config = { pad: "ø".repeat(20), endpoint: "https://example.com/api", interval: 10 }
+ const encoded = encodeConfig(config)
+ const asReceived = encoded.replace(/\+/g, " ")
+ expect(asReceived).not.toBe(encoded) // proves the payload's base64 actually contained a '+'
+ expect(decodeConfig(asReceived)).toEqual(config)
+ })
+})
diff --git a/apps/mobile/src/utils/setupConfig.ts b/apps/mobile/src/utils/setupConfig.ts
new file mode 100644
index 00000000..23dc298c
--- /dev/null
+++ b/apps/mobile/src/utils/setupConfig.ts
@@ -0,0 +1,361 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX, defaultProfileDelays, PROFILE_CONDITIONS } from "../constants"
+import { isEndpointAllowed } from "./settingsValidation"
+import {
+ TRACKING_PRESETS,
+ API_TEMPLATES,
+ type Settings,
+ type AuthConfig,
+ type FieldMap,
+ type CustomField,
+ type ApiTemplateName,
+ type HttpMethod,
+ type DawarichMode,
+ type SelectablePreset,
+ type SyncPreset,
+ type Geofence,
+ type TrackingProfile,
+ type ProfileConditionType,
+ type AuthType
+} from "../types/global"
+
+export type ImportGeofence = Omit<Geofence, "id" | "createdAt">
+export type ImportProfile = Omit<TrackingProfile, "id" | "createdAt">
+
+export interface ParsedConfig {
+ settings: Partial<Settings>
+ auth: Partial<AuthConfig> | null
+ geofences: ImportGeofence[]
+ profiles: ImportProfile[]
+}
+
+export interface ConfigEntry {
+ label: string
+ value: string
+ category: "tracking" | "api" | "auth" | "geofence" | "profile"
+ rejected?: boolean
+}
+
+export interface ValidationResult {
+ valid: boolean
+ config: ParsedConfig
+ entries: ConfigEntry[]
+ error?: string
+}
+
+const VALID_API_TEMPLATES = ["custom", ...Object.keys(API_TEMPLATES)] as ApiTemplateName[]
+const VALID_HTTP_METHODS: HttpMethod[] = ["POST", "GET"]
+const VALID_DAWARICH_MODES: DawarichMode[] = ["single", "batch"]
+const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]
+
+const VALID_PROFILE_CONDITIONS = PROFILE_CONDITIONS.map((c) => c.type)
+
+export function detectPreset(settings: Partial<Settings>): SyncPreset {
+ for (const [name, config] of Object.entries(TRACKING_PRESETS)) {
+ if (
+ settings.interval === config.interval &&
+ settings.distance === config.distance &&
+ settings.syncInterval === config.syncInterval &&
+ settings.retryInterval === config.retryInterval
+ ) {
+ return name as SelectablePreset
+ }
+ }
+ return "custom"
+}
+
+export function validateConfig(raw: unknown): ValidationResult {
+ if (!raw || typeof raw !== "object") {
+ return {
+ valid: false,
+ config: { settings: {}, auth: null, geofences: [], profiles: [] },
+ entries: [],
+ error: "Invalid configuration format"
+ }
+ }
+
+ const obj = raw as Record<string, unknown>
+ const settings: Partial<Settings> = {}
+ const entries: ConfigEntry[] = []
+ let auth: Partial<AuthConfig> | null = null
+
+ // --- API settings (endpoint) ---
+
+ if ("endpoint" in obj && typeof obj.endpoint === "string" && obj.endpoint.length > 0) {
+ if (isEndpointAllowed(obj.endpoint)) {
+ settings.endpoint = obj.endpoint
+ entries.push({ label: "Endpoint", value: obj.endpoint, category: "api" })
+ } else {
+ entries.push({ label: "Endpoint", value: "HTTP not allowed for public hosts", category: "api", rejected: true })
+ }
+ }
+
+ // --- Tracking settings ---
+
+ if ("interval" in obj && typeof obj.interval === "number" && obj.interval > 0) {
+ settings.interval = obj.interval
+ entries.push({ label: "Interval", value: `${obj.interval}s`, category: "tracking" })
+ }
+
+ if ("distance" in obj && typeof obj.distance === "number" && obj.distance >= 0) {
+ settings.distance = obj.distance
+ entries.push({ label: "Distance threshold", value: `${obj.distance}m`, category: "tracking" })
+ }
+
+ if ("syncInterval" in obj && typeof obj.syncInterval === "number" && obj.syncInterval >= 0) {
+ settings.syncInterval = obj.syncInterval
+ entries.push({
+ label: "Sync interval",
+ value: obj.syncInterval === 0 ? "Instant" : `${obj.syncInterval}s`,
+ category: "tracking"
+ })
+ }
+
+ if ("retryInterval" in obj && typeof obj.retryInterval === "number" && obj.retryInterval >= 0) {
+ settings.retryInterval = obj.retryInterval
+ entries.push({ label: "Retry interval", value: `${obj.retryInterval}s`, category: "tracking" })
+ }
+
+ if ("accuracyThreshold" in obj && typeof obj.accuracyThreshold === "number" && obj.accuracyThreshold > 0) {
+ settings.accuracyThreshold = obj.accuracyThreshold
+ entries.push({ label: "Accuracy threshold", value: `${obj.accuracyThreshold}m`, category: "tracking" })
+ }
+
+ if ("filterInaccurateLocations" in obj && typeof obj.filterInaccurateLocations === "boolean") {
+ settings.filterInaccurateLocations = obj.filterInaccurateLocations
+ entries.push({
+ label: "Filter inaccurate",
+ value: obj.filterInaccurateLocations ? "Yes" : "No",
+ category: "tracking"
+ })
+ }
+
+ if ("isOfflineMode" in obj && typeof obj.isOfflineMode === "boolean") {
+ settings.isOfflineMode = obj.isOfflineMode
+ entries.push({ label: "Offline mode", value: obj.isOfflineMode ? "Yes" : "No", category: "tracking" })
+ }
+
+ if ("syncCondition" in obj && typeof obj.syncCondition === "string") {
+ settings.syncCondition = obj.syncCondition as any
+ entries.push({ label: "Sync condition", value: obj.syncCondition, category: "tracking" })
+ }
+
+ if ("syncSsid" in obj && typeof obj.syncSsid === "string") {
+ settings.syncSsid = obj.syncSsid
+ entries.push({ label: "Sync SSID", value: obj.syncSsid, category: "tracking" })
+ }
+
+ // --- API settings ---
+
+ if (
+ "apiTemplate" in obj &&
+ typeof obj.apiTemplate === "string" &&
+ VALID_API_TEMPLATES.includes(obj.apiTemplate as ApiTemplateName)
+ ) {
+ settings.apiTemplate = obj.apiTemplate as ApiTemplateName
+ entries.push({ label: "API template", value: obj.apiTemplate, category: "api" })
+ }
+
+ if (
+ "httpMethod" in obj &&
+ typeof obj.httpMethod === "string" &&
+ VALID_HTTP_METHODS.includes(obj.httpMethod as HttpMethod)
+ ) {
+ settings.httpMethod = obj.httpMethod as HttpMethod
+ entries.push({ label: "HTTP method", value: obj.httpMethod, category: "api" })
+ }
+
+ if (
+ "dawarichMode" in obj &&
+ typeof obj.dawarichMode === "string" &&
+ VALID_DAWARICH_MODES.includes(obj.dawarichMode as DawarichMode)
+ ) {
+ settings.dawarichMode = obj.dawarichMode as DawarichMode
+ entries.push({ label: "Dawarich mode", value: obj.dawarichMode, category: "api" })
+ }
+
+ if (
+ "overlandBatchSize" in obj &&
+ typeof obj.overlandBatchSize === "number" &&
+ obj.overlandBatchSize >= OVERLAND_BATCH_MIN &&
+ obj.overlandBatchSize <= OVERLAND_BATCH_MAX
+ ) {
+ settings.overlandBatchSize = Math.floor(obj.overlandBatchSize)
+ entries.push({ label: "Overland batch size", value: String(settings.overlandBatchSize), category: "api" })
+ }
+
+ if ("fieldMap" in obj && typeof obj.fieldMap === "object" && obj.fieldMap !== null) {
+ const fm = obj.fieldMap as Record<string, unknown>
+ const validFieldMap: Partial<FieldMap> = {}
+ let hasValid = false
+ for (const [key, val] of Object.entries(fm)) {
+ if (typeof val === "string") {
+ ;(validFieldMap as any)[key] = val
+ hasValid = true
+ }
+ }
+ if (hasValid) {
+ settings.fieldMap = validFieldMap as FieldMap
+ entries.push({ label: "Field mapping", value: `${Object.keys(validFieldMap).length} fields`, category: "api" })
+ }
+ }
+
+ if ("customFields" in obj && Array.isArray(obj.customFields)) {
+ const validFields: CustomField[] = obj.customFields.filter(
+ (f: any) => f && typeof f.key === "string" && typeof f.value === "string" && f.key.length > 0
+ )
+ if (validFields.length > 0) {
+ settings.customFields = validFields
+ entries.push({ label: "Custom fields", value: `${validFields.length} fields`, category: "api" })
+ }
+ }
+
+ // --- Auth settings ---
+
+ if ("auth" in obj && typeof obj.auth === "object" && obj.auth !== null) {
+ const authObj = obj.auth as Record<string, unknown>
+ auth = {}
+
+ if ("type" in authObj && typeof authObj.type === "string" && VALID_AUTH_TYPES.includes(authObj.type as AuthType)) {
+ auth.authType = authObj.type as AuthType
+ entries.push({ label: "Auth type", value: authObj.type, category: "auth" })
+ }
+
+ if ("username" in authObj && typeof authObj.username === "string" && authObj.username.length > 0) {
+ auth.username = authObj.username
+ entries.push({ label: "Username", value: authObj.username, category: "auth" })
+ }
+
+ if ("password" in authObj && typeof authObj.password === "string" && authObj.password.length > 0) {
+ auth.password = authObj.password
+ entries.push({ label: "Password", value: "•".repeat(8), category: "auth" })
+ }
+
+ if ("bearerToken" in authObj && typeof authObj.bearerToken === "string" && authObj.bearerToken.length > 0) {
+ auth.bearerToken = authObj.bearerToken
+ const masked =
+ authObj.bearerToken.length > 8
+ ? authObj.bearerToken.slice(0, 4) + "•".repeat(4) + authObj.bearerToken.slice(-4)
+ : "•".repeat(authObj.bearerToken.length)
+ entries.push({ label: "Bearer token", value: masked, category: "auth" })
+ }
+
+ if (Object.keys(auth).length === 0) auth = null
+ }
+
+ if ("customHeaders" in obj && typeof obj.customHeaders === "object" && obj.customHeaders !== null) {
+ const headers = obj.customHeaders as Record<string, unknown>
+ const validHeaders: Record<string, string> = {}
+ for (const [key, val] of Object.entries(headers)) {
+ if (typeof val === "string") {
+ validHeaders[key] = val
+ }
+ }
+ if (Object.keys(validHeaders).length > 0) {
+ if (!auth) auth = {}
+ auth.customHeaders = validHeaders
+ entries.push({ label: "Custom headers", value: `${Object.keys(validHeaders).length} headers`, category: "auth" })
+ }
+ }
+
+ // --- Geofences ---
+
+ const geofences: ImportGeofence[] = []
+
+ if ("geofences" in obj && Array.isArray(obj.geofences)) {
+ for (const entry of obj.geofences) {
+ if (!entry || typeof entry !== "object") continue
+ const g = entry as Record<string, unknown>
+ if (
+ typeof g.name !== "string" ||
+ g.name.length === 0 ||
+ typeof g.lat !== "number" ||
+ typeof g.lon !== "number" ||
+ typeof g.radius !== "number" ||
+ g.radius <= 0
+ ) {
+ continue
+ }
+ geofences.push({
+ name: g.name,
+ lat: g.lat,
+ lon: g.lon,
+ radius: g.radius,
+ enabled: typeof g.enabled === "boolean" ? g.enabled : true,
+ pauseTracking: typeof g.pauseTracking === "boolean" ? g.pauseTracking : false,
+ pauseOnWifi: typeof g.pauseOnWifi === "boolean" ? g.pauseOnWifi : false,
+ pauseOnMotionless: typeof g.pauseOnMotionless === "boolean" ? g.pauseOnMotionless : false,
+ motionlessTimeoutMinutes: typeof g.motionlessTimeoutMinutes === "number" ? g.motionlessTimeoutMinutes : 10,
+ heartbeatEnabled: typeof g.heartbeatEnabled === "boolean" ? g.heartbeatEnabled : false,
+ heartbeatIntervalMinutes: typeof g.heartbeatIntervalMinutes === "number" ? g.heartbeatIntervalMinutes : 15
+ })
+ entries.push({ label: g.name, value: `${g.radius}m`, category: "geofence" })
+ }
+ }
+
+ // --- Tracking Profiles ---
+
+ const profiles: ImportProfile[] = []
+
+ if ("profiles" in obj && Array.isArray(obj.profiles)) {
+ for (const entry of obj.profiles) {
+ if (!entry || typeof entry !== "object") continue
+ const p = entry as Record<string, unknown>
+ if (
+ typeof p.name !== "string" ||
+ p.name.length === 0 ||
+ typeof p.interval !== "number" ||
+ p.interval < 1 ||
+ typeof p.distance !== "number" ||
+ p.distance < 0 ||
+ typeof p.syncInterval !== "number" ||
+ p.syncInterval < 0
+ ) {
+ continue
+ }
+
+ const condRaw = p.condition as Record<string, unknown> | undefined
+ if (!condRaw || typeof condRaw !== "object" || typeof condRaw.type !== "string") continue
+ if (!VALID_PROFILE_CONDITIONS.includes(condRaw.type as ProfileConditionType)) continue
+ const condType = condRaw.type as ProfileConditionType
+ const needsSpeed = condType === "speed_above" || condType === "speed_below"
+ if (needsSpeed && (typeof condRaw.speedThreshold !== "number" || condRaw.speedThreshold <= 0)) continue
+ const condition: TrackingProfile["condition"] = needsSpeed
+ ? { type: condType, speedThreshold: condRaw.speedThreshold as number }
+ : { type: condType }
+
+ const delays = defaultProfileDelays(condType)
+ profiles.push({
+ name: p.name,
+ interval: p.interval,
+ distance: p.distance,
+ syncInterval: p.syncInterval,
+ priority: typeof p.priority === "number" ? p.priority : 10,
+ activationDelay:
+ typeof p.activationDelay === "number" && p.activationDelay >= 0 ? p.activationDelay : delays.activationDelay,
+ deactivationDelay:
+ typeof p.deactivationDelay === "number" && p.deactivationDelay >= 0
+ ? p.deactivationDelay
+ : delays.deactivationDelay,
+ enabled: typeof p.enabled === "boolean" ? p.enabled : true,
+ condition
+ })
+ entries.push({ label: p.name, value: `${p.interval}s`, category: "profile" })
+ }
+ }
+
+ if (entries.length === 0) {
+ return {
+ valid: false,
+ config: { settings, auth, geofences, profiles },
+ entries,
+ error: "No valid settings found in configuration"
+ }
+ }
+
+ return { valid: true, config: { settings, auth, geofences, profiles }, entries }
+}
diff --git a/apps/mobile/src/utils/setupLink.ts b/apps/mobile/src/utils/setupLink.ts
new file mode 100644
index 00000000..b08b7cce
--- /dev/null
+++ b/apps/mobile/src/utils/setupLink.ts
@@ -0,0 +1,123 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import type { Settings, AuthConfig, Geofence, TrackingProfile } from "../types/global"
+
+/** Which config categories to include in a shared setup link. */
+export interface SetupShareSelection {
+ tracking: boolean
+ sync: boolean
+ api: boolean
+ credentials: boolean
+ geofences: boolean
+ profiles: boolean
+}
+
+/** Live config read from the running app, used to build a setup link. */
+export interface SetupShareParts {
+ settings: Settings
+ auth: AuthConfig
+ geofences: Geofence[]
+ profiles: TrackingProfile[]
+}
+
+/**
+ * Builds the config object the importer's `validateConfig` accepts, including only the selected
+ * categories. The standalone Geofences/Profiles share buttons reuse this too.
+ */
+export function buildSetupConfig(parts: SetupShareParts, sel: SetupShareSelection): Record<string, unknown> {
+ const { settings, auth, geofences, profiles } = parts
+ const config: Record<string, unknown> = {}
+
+ if (sel.tracking) {
+ config.interval = settings.interval
+ config.distance = settings.distance
+ config.accuracyThreshold = settings.accuracyThreshold
+ config.filterInaccurateLocations = settings.filterInaccurateLocations
+ }
+
+ if (sel.sync) {
+ config.syncInterval = settings.syncInterval
+ config.retryInterval = settings.retryInterval
+ config.isOfflineMode = settings.isOfflineMode
+ config.syncCondition = settings.syncCondition
+ if (settings.syncSsid) config.syncSsid = settings.syncSsid
+ }
+
+ if (sel.api) {
+ if (settings.endpoint) config.endpoint = settings.endpoint
+ config.apiTemplate = settings.apiTemplate
+ config.httpMethod = settings.httpMethod
+ config.dawarichMode = settings.dawarichMode
+ config.overlandBatchSize = settings.overlandBatchSize
+ if (settings.fieldMap && Object.keys(settings.fieldMap).length > 0) config.fieldMap = settings.fieldMap
+ if (settings.customFields && settings.customFields.length > 0) config.customFields = settings.customFields
+ }
+
+ // Importer expects `auth.type` (not `authType`) and top-level `customHeaders`.
+ if (sel.credentials) {
+ const a: Record<string, unknown> = { type: auth.authType }
+ if (auth.authType === "basic") {
+ if (auth.username) a.username = auth.username
+ if (auth.password) a.password = auth.password
+ } else if (auth.authType === "bearer") {
+ if (auth.bearerToken) a.bearerToken = auth.bearerToken
+ }
+ config.auth = a
+ if (auth.customHeaders && Object.keys(auth.customHeaders).length > 0) {
+ config.customHeaders = auth.customHeaders
+ }
+ }
+
+ if (sel.geofences && geofences.length > 0) {
+ config.geofences = geofences.map(stripGeofence)
+ }
+
+ if (sel.profiles && profiles.length > 0) {
+ config.profiles = profiles.map(stripProfile)
+ }
+
+ return config
+}
+
+/** Builds the full `colota://setup?config=...` deep link for the selected categories. */
+export function buildSetupLink(parts: SetupShareParts, sel: SetupShareSelection): string {
+ return encode(buildSetupConfig(parts, sel))
+}
+
+/** Single-category link for the standalone Geofences share button. */
+export function buildGeofencesLink(geofences: Geofence[]): string {
+ return encode({ geofences: geofences.map(stripGeofence) })
+}
+
+/** Single-category link for the standalone Tracking Profiles share button. */
+export function buildProfilesLink(profiles: TrackingProfile[]): string {
+ return encode({ profiles: profiles.map(stripProfile) })
+}
+
+// Strip DB-only fields (id/createdAt, plus enabled for geofences - the importer defaults it to true).
+function stripGeofence({ id: _id, createdAt: _createdAt, enabled: _enabled, ...rest }: Geofence) {
+ return rest
+}
+
+function stripProfile({ id: _id, createdAt: _createdAt, ...rest }: TrackingProfile) {
+ return rest
+}
+
+function encode(config: Record<string, unknown>): string {
+ return `colota://setup?config=${encodeConfig(config)}`
+}
+
+export function encodeConfig(config: unknown): string {
+ return btoa(JSON.stringify(config))
+}
+
+/**
+ * Decodes a setup-link `config` param. React Navigation's query parser decodes `+` as a space, and
+ * base64 never contains spaces, so any space here was a `+` - restore it before decoding.
+ */
+export function decodeConfig(param: string): unknown {
+ return JSON.parse(atob(param.replace(/ /g, "+")))
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/41.txt b/fastlane/metadata/android/en-US/changelogs/41.txt
new file mode 100644
index 00000000..f1d9fa53
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/41.txt
@@ -0,0 +1 @@
+- Share your setup as a link: pick which settings, geofences and profiles to include from the new Share Setup screen in Settings.