Add Kismet Wi-Fi and Bluetooth wardriving
This commit is contained in:
1 parent
972deb93df
commit
ec11b02a03
26 files changed
+1851
-22
No files matched your search
@@ -20,6 +20,18 @@ NETWORK_HOTSPOT_CONNECTION=pi-car-hotspot
|
||||
NETWORK_PROBE_TIMEOUT_SECONDS=60
|
||||
NETWORK_STABILITY_SECONDS=10
|
||||
NETWORK_POLL_SECONDS=5
|
||||
# On a Raspberry Pi install this is enabled, but capture still starts only when
|
||||
# a user explicitly starts a session from the Wardriving UI.
|
||||
WARDRIVING_ENABLED=false
|
||||
WARDRIVING_STATUS_PATH=/var/lib/pi-car-companion/wardriving-status.json
|
||||
WARDRIVING_KISMET_URL=http://127.0.0.1:2501
|
||||
WARDRIVING_KISMET_AUTH_PATH=/var/lib/pi-car-companion/kismet/kismet-api-credentials.json
|
||||
WARDRIVING_POLL_SECONDS=5
|
||||
WARDRIVING_MAX_SIGHTINGS=250000
|
||||
# Leave WiFi empty for automatic selection of a third adapter. Never use wlan0
|
||||
# (hotspot) or wlan1 (upstream). Set Bluetooth empty to disable its source.
|
||||
WARDRIVING_WIFI_INTERFACE=
|
||||
WARDRIVING_BLUETOOTH_INTERFACE=hci0
|
||||
# Disabled by default. Leave ADB_SERIAL empty to auto-select only when exactly one device is attached.
|
||||
ADB_ENABLED=false
|
||||
ADB_PATH=adb
|
||||
|
||||
@@ -21,6 +21,7 @@ The current MVP slice includes:
|
||||
- atomic, dashboard-triggered Git updates with automatic verification and rollback safety;
|
||||
- optional dual-radio Wi-Fi failover with an always-recoverable offline car hotspot;
|
||||
- authenticated live network diagnostics for hotspot clients, DNS query metadata, and active destination flows;
|
||||
- opt-in WiFi and Bluetooth wardriving through Kismet (passive WiFi and discoverable Bluetooth metadata), with phone GPS association and a live map;
|
||||
- tabbed Network, System, and restricted Shell settings for on-device administration;
|
||||
- automated API security tests and reproducible quality commands.
|
||||
|
||||
@@ -46,7 +47,7 @@ cd pi-car-companion
|
||||
|
||||
The script asks for sudo access and then:
|
||||
|
||||
- installs Node.js 22, Git, Avahi, SQLite, the complete hotspot/Realtek networking stack, and native build requirements;
|
||||
- installs Node.js 22, Git, Avahi, SQLite, Kismet, the complete hotspot/Realtek networking stack, and native build requirements;
|
||||
- creates a dedicated `pi-companion` service account;
|
||||
- builds and verifies the server and dashboard;
|
||||
- installs an atomic release under `/opt/pi-car-companion`;
|
||||
@@ -171,6 +172,19 @@ Important values:
|
||||
- `NETWORK_ACTIVITY_PATH`: bounded observer snapshot consumed by the authenticated dashboard
|
||||
- `NETWORK_HOTSPOT_INTERFACE` / `NETWORK_UPSTREAM_INTERFACE`: default to built-in `wlan0` and USB `wlan1`
|
||||
- `NETWORK_PROBE_TIMEOUT_SECONDS`: maximum built-in upstream attempt before restoring the offline hotspot
|
||||
- `WARDRIVING_ENABLED`: enables the opt-in Kismet session controller; the installer sets this to `true` on Raspberry Pi deployments
|
||||
- `WARDRIVING_KISMET_URL`: local Kismet API URL, normally `http://127.0.0.1:2501`
|
||||
- `WARDRIVING_WIFI_INTERFACE`: dedicated monitor-mode WiFi interface; when empty, the installer auto-selects a third WiFi adapter and never commandeers `wlan0` or `wlan1`
|
||||
- `WARDRIVING_BLUETOOTH_INTERFACE`: Bluetooth adapter used by Kismet, normally `hci0`
|
||||
- `WARDRIVING_POLL_SECONDS` / `WARDRIVING_MAX_SIGHTINGS`: Kismet polling interval and bounded observation retention
|
||||
|
||||
### WiFi + Bluetooth wardriving
|
||||
|
||||
The installer installs Kismet and a manually controlled `pi-car-companion-kismet.service`. It does not start capture at boot. Open **Wardriving** in the dashboard (or the Android companion), pair a phone, and start a session when the vehicle is parked or moving in a place where discovery is lawful. The official Kismet repository currently provides the required capture packages for 64-bit Raspberry Pi OS; the installer stops with an explicit architecture message on unsupported 32-bit images.
|
||||
|
||||
Use a dedicated USB WiFi adapter that supports monitor mode. Keep the built-in `wlan0` on the car hotspot and the upstream adapter on `wlan1`; set `WARDRIVING_WIFI_INTERFACE` to a third adapter where possible. Bluetooth capture uses the Pi's `hci0` adapter by default and Kismet's discoverable-device scan; a second Bluetooth adapter can be selected with `WARDRIVING_BLUETOOTH_INTERFACE` if the companion BLE link needs its own controller. It does not pair with devices or enumerate services. Kismet is configured for live device tracking without retaining raw packet payloads. Pi Car Companion stores bounded sightings and joins them to a phone GPS fix only while that fix is fresh and accurate. Observations without a suitable fix remain visible but are marked unmapped.
|
||||
|
||||
The UI exposes the active session, Kismet and GPS health, WiFi/Bluetooth counts, recent device metadata, a Leaflet map of mapped sightings, session controls, and data clearing. The Android app shows the same live summary over its existing Bluetooth bridge and can start or stop the session. Revoke a paired phone in **Settings → Mobile** to stop it contributing location data.
|
||||
|
||||
### Dual-radio car network
|
||||
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ The Android app is a focused native companion rather than a copy of the web dash
|
||||
- live car speed, gear, steering, battery, range, and lifetime statistics;
|
||||
- launch access to ADB shortcuts that were explicitly saved in the web dashboard;
|
||||
- phone GPS, speed, bearing, accuracy, battery, and network-state uplink;
|
||||
- live WiFi/Bluetooth wardriving counts, GPS mapping health, recent devices, and start/stop/restart controls;
|
||||
- background BLE reconnection and location updates through a foreground service.
|
||||
|
||||
## Pairing
|
||||
@@ -30,4 +31,4 @@ The debug APK is copied to [`apks/pi-car-companion-debug.apk`](../apks/pi-car-co
|
||||
|
||||
## BLE protocol
|
||||
|
||||
The custom service UUID is `6c7a0001-7c6d-4f74-9bb0-c5a4e5efc001`. RX and TX carry newline-delimited UTF-8 JSON, fragmented into BLE-sized chunks. Protocol version 1 exposes only `pair`, `snapshot`, `location`, and `launchShortcut` operations. Android sends GPS at most every second and refreshes the dashboard snapshot every five seconds.
|
||||
The custom service UUID is `6c7a0001-7c6d-4f74-9bb0-c5a4e5efc001`. RX and TX carry newline-delimited UTF-8 JSON, fragmented into BLE-sized chunks. Protocol version 1 exposes `pair`, `snapshot`, `location`, `wardriving`, and `launchShortcut` operations. Android sends GPS at most every second and refreshes the dashboard snapshot every five seconds. Wardriving controls are limited to a paired phone; WiFi capture is passive and Bluetooth uses discoverable-device metadata scanning only.
|
||||
@@ -1,9 +1,12 @@
|
||||
package cloud.molberg.picar
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import com.google.android.gms.location.*
|
||||
import kotlinx.coroutines.*
|
||||
@@ -29,6 +32,18 @@ class CompanionRepository(private val context: Context) {
|
||||
} }
|
||||
}
|
||||
|
||||
fun hasRequiredPermissions(): Boolean {
|
||||
val required = buildList {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
add(Manifest.permission.BLUETOOTH_SCAN)
|
||||
add(Manifest.permission.BLUETOOTH_CONNECT)
|
||||
}
|
||||
add(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
return required.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
|
||||
}
|
||||
|
||||
fun connect() = ble.connect()
|
||||
fun stop() { polling?.cancel(); ble.disconnect() }
|
||||
|
||||
@@ -62,6 +77,26 @@ class CompanionRepository(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun wardrivingAction(action: String) {
|
||||
val token = tokenStore.load() ?: return
|
||||
scope.launch {
|
||||
mutableState.value = mutableState.value.copy(busyWardriving = true, error = null)
|
||||
val result = runCatching { parseWardriving(ble.request("wardriving", token, JSONObject().put("action", action))) }
|
||||
val radio = result.getOrNull()
|
||||
if (radio != null) {
|
||||
val current = mutableState.value.snapshot
|
||||
if (current != null) {
|
||||
mutableState.value = mutableState.value.copy(snapshot = current.copy(wardriving = radio), error = null)
|
||||
} else {
|
||||
fetchSnapshot()
|
||||
}
|
||||
} else {
|
||||
mutableState.value = mutableState.value.copy(error = result.exceptionOrNull()?.message)
|
||||
}
|
||||
mutableState.value = mutableState.value.copy(busyWardriving = false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startPolling() {
|
||||
polling?.cancel()
|
||||
polling = scope.launch {
|
||||
@@ -134,6 +169,8 @@ class CompanionRepository(private val context: Context) {
|
||||
fun availableString(name: String) = car?.optJSONObject(name)?.takeIf { it.optBoolean("available") }?.optString("value")
|
||||
val shortcutsJson = json.getJSONArray("shortcuts")
|
||||
val shortcuts = (0 until shortcutsJson.length()).map { index -> shortcutsJson.getJSONObject(index).let { Shortcut(it.getInt("id"), it.getString("name"), it.getString("value")) } }
|
||||
val wardrivingJson = json.optJSONObject("wardriving")
|
||||
val wardriving = parseWardriving(wardrivingJson)
|
||||
return Snapshot(
|
||||
json.getString("collectedAt"),
|
||||
SystemSummary(
|
||||
@@ -148,7 +185,48 @@ class CompanionRepository(private val context: Context) {
|
||||
availableNumber("batteryPercent"), availableNumber("rangeKm"), availableNumber("batteryVoltage"),
|
||||
availableNumber("totalConsumptionKwh"), lifetime.optDouble("trackedDistanceKm", 0.0),
|
||||
lifetime.optNullableDouble("averageMovingSpeedKph"), records.optNullableDouble("peakSpeedKph")),
|
||||
shortcuts
|
||||
shortcuts,
|
||||
wardriving
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseWardriving(wardrivingJson: JSONObject?): WardrivingSummary {
|
||||
val wardrivingStats = wardrivingJson?.optJSONObject("statistics")
|
||||
val wardrivingGps = wardrivingJson?.optJSONObject("gps")
|
||||
val gpsFix = wardrivingGps?.optJSONObject("fix")
|
||||
val devicesJson = wardrivingJson?.optJSONArray("devices")
|
||||
val devices = if (devicesJson == null) emptyList() else (0 until minOf(devicesJson.length(), 12)).map { index ->
|
||||
val device = devicesJson.getJSONObject(index)
|
||||
WardrivingDevice(
|
||||
device.optString("technology", "other"),
|
||||
device.optString("displayName").takeIf { it.isNotBlank() } ?: device.optString("ssid").takeIf { it.isNotBlank() } ?: "Unnamed device",
|
||||
device.optString("macAddress").takeIf { it.isNotBlank() },
|
||||
device.optString("channel").takeIf { it.isNotBlank() },
|
||||
device.optString("lastSeenAt")
|
||||
)
|
||||
}
|
||||
val sightingsJson = wardrivingJson?.optJSONArray("sightings")
|
||||
val mappedPoints = if (sightingsJson == null) emptyList() else (0 until minOf(sightingsJson.length(), 30)).mapNotNull { index ->
|
||||
val sighting = sightingsJson.getJSONObject(index)
|
||||
if (sighting.isNull("latitude") || sighting.isNull("longitude")) null else WardrivingPoint(
|
||||
sighting.getDouble("latitude"), sighting.getDouble("longitude"), sighting.optString("technology", "other"),
|
||||
sighting.optString("displayName").takeIf { it.isNotBlank() } ?: sighting.optString("macAddress", "Device"), sighting.optString("observedAt")
|
||||
)
|
||||
}
|
||||
return WardrivingSummary(
|
||||
enabled = wardrivingJson?.optBoolean("enabled", false) ?: false,
|
||||
running = wardrivingJson?.optBoolean("running", false) ?: false,
|
||||
kismetAvailable = wardrivingJson?.optJSONObject("kismet")?.optBoolean("available", false) ?: false,
|
||||
kismetMessage = wardrivingJson?.optJSONObject("kismet")?.optString("message", "Kismet is not available") ?: "Kismet is not available",
|
||||
gpsAvailable = wardrivingGps?.optBoolean("available", false) ?: false,
|
||||
gpsAccuracyMeters = gpsFix?.optNullableDouble("accuracyMeters"),
|
||||
gpsMessage = wardrivingGps?.optString("message", "Pair a phone to map observations") ?: "Pair a phone to map observations",
|
||||
wifiDevices = wardrivingStats?.optInt("wifiDevices", 0) ?: 0,
|
||||
bluetoothDevices = wardrivingStats?.optInt("bluetoothDevices", 0) ?: 0,
|
||||
sightings = wardrivingStats?.optInt("sightings", 0) ?: 0,
|
||||
mappedSightings = wardrivingStats?.optInt("mappedSightings", 0) ?: 0,
|
||||
devices = devices,
|
||||
mappedPoints = mappedPoints
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ class CompanionService : Service() {
|
||||
val notification = Notification.Builder(this, channel.id)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
|
||||
.setContentTitle("Pi Car Companion")
|
||||
.setContentText("Bluetooth and phone GPS are active")
|
||||
.setContentText("Bluetooth, phone GPS, and radio mapping are ready")
|
||||
.setContentIntent(launch)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
|
||||
@@ -2,7 +2,6 @@ package cloud.molberg.picar
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -43,11 +42,22 @@ class MainActivity : ComponentActivity() {
|
||||
add(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}.toTypedArray()
|
||||
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants -> if (grants.values.all { it }) startService() }
|
||||
var permissionsGranted by remember {
|
||||
mutableStateOf(repository.hasRequiredPermissions())
|
||||
}
|
||||
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants ->
|
||||
permissionsGranted = grants.values.all { it }
|
||||
if (permissionsGranted) startService()
|
||||
}
|
||||
LaunchedEffect(Unit) { launcher.launch(permissions) }
|
||||
LaunchedEffect(state.paired, permissionsGranted) {
|
||||
// A paired phone must restart its foreground service after the app is
|
||||
// opened again; otherwise no BLE connection or GPS handoff exists.
|
||||
if (state.paired && permissionsGranted) startService()
|
||||
}
|
||||
|
||||
if (!state.paired) PairScreen(state, onConnect = startService, onPair = repository::pair)
|
||||
else Dashboard(state, repository::refresh, repository::launchShortcut, repository::forget)
|
||||
else Dashboard(state, repository::refresh, repository::launchShortcut, repository::wardrivingAction, repository::forget)
|
||||
}
|
||||
|
||||
@Composable private fun PairScreen(state: CompanionUiState, onConnect: () -> Unit, onPair: (String, (Boolean) -> Unit) -> Unit) {
|
||||
@@ -66,11 +76,11 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable private fun Dashboard(state: CompanionUiState, refresh: () -> Unit, launch: (Shortcut) -> Unit, forget: () -> Unit) {
|
||||
@Composable private fun Dashboard(state: CompanionUiState, refresh: () -> Unit, launch: (Shortcut) -> Unit, wardrivingAction: (String) -> Unit, forget: () -> Unit) {
|
||||
var tab by remember { mutableIntStateOf(0) }
|
||||
Scaffold(containerColor = Bg, bottomBar = {
|
||||
NavigationBar(containerColor = Surface) {
|
||||
listOf("Overview", "Car", "Controls").forEachIndexed { index, title -> NavigationBarItem(selected = tab == index, onClick = { tab = index }, icon = { Text(listOf("●", "◆", "▶")[index]) }, label = { Text(title) }, colors = NavigationBarItemDefaults.colors(selectedIconColor = Accent, selectedTextColor = Text, indicatorColor = Raised, unselectedIconColor = Muted, unselectedTextColor = Muted)) }
|
||||
listOf("Overview", "Car", "Radio", "Controls").forEachIndexed { index, title -> NavigationBarItem(selected = tab == index, onClick = { tab = index }, icon = { Text(listOf("●", "◆", "⌁", "▶")[index]) }, label = { Text(title) }, colors = NavigationBarItemDefaults.colors(selectedIconColor = Accent, selectedTextColor = Text, indicatorColor = Raised, unselectedIconColor = Muted, unselectedTextColor = Muted)) }
|
||||
}
|
||||
}) { padding ->
|
||||
Column(Modifier.padding(padding).padding(horizontal = 18.dp).fillMaxSize()) {
|
||||
@@ -82,6 +92,7 @@ class MainActivity : ComponentActivity() {
|
||||
when (tab) {
|
||||
0 -> OverviewScreen(state.snapshot, refresh)
|
||||
1 -> CarScreen(state.snapshot?.car)
|
||||
2 -> WardrivingScreen(state, wardrivingAction)
|
||||
else -> ControlsScreen(state, launch, forget)
|
||||
}
|
||||
}
|
||||
@@ -106,6 +117,80 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable private fun WardrivingScreen(state: CompanionUiState, action: (String) -> Unit) {
|
||||
val radio = state.snapshot?.wardriving
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp), contentPadding = PaddingValues(bottom = 20.dp)) {
|
||||
item {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Surface), shape = RoundedCornerShape(18.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(22.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("RADIO MAP", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.5.sp)
|
||||
Text(if (radio?.running == true) "Session live" else "Session idle", color = Text, fontSize = 26.sp, fontWeight = FontWeight.Bold)
|
||||
Text(if (radio?.running == true) "Kismet is collecting WiFi and discoverable Bluetooth metadata." else "Start a session from the phone or Pi dashboard when you are ready.", color = Muted, lineHeight = 21.sp)
|
||||
}
|
||||
Text(if (radio?.running == true) "●" else "○", color = if (radio?.running == true) Accent else Muted, fontSize = 28.sp)
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Button(onClick = { action(if (radio?.running == true) "stop" else "start") }, enabled = !state.busyWardriving && radio?.enabled == true, modifier = Modifier.weight(1f).height(52.dp), colors = ButtonDefaults.buttonColors(containerColor = if (radio?.running == true) Raised else Accent, contentColor = if (radio?.running == true) Text else AccentInk)) { Text(if (state.busyWardriving) "Working…" else if (radio?.running == true) "Stop session" else "Start session", fontWeight = FontWeight.Bold) }
|
||||
OutlinedButton(onClick = { action("restart") }, enabled = !state.busyWardriving && radio?.running == true, modifier = Modifier.height(52.dp), colors = ButtonDefaults.outlinedButtonColors(contentColor = Text)) { Text("Restart") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Box(Modifier.weight(1f)) { MetricCard("WiFi", radio?.wifiDevices?.toString() ?: "--", "Networks seen", Accent) }
|
||||
Box(Modifier.weight(1f)) { MetricCard("Bluetooth", radio?.bluetoothDevices?.toString() ?: "--", "Devices seen", Color(0xFF8BC4FF)) }
|
||||
}
|
||||
}
|
||||
item {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Surface), shape = RoundedCornerShape(14.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp)) {
|
||||
Text("GPS handoff", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(if (radio?.gpsAvailable == true) "Phone location is mapping observations" else "Waiting for a phone location fix", color = Text, fontSize = 17.sp, fontWeight = FontWeight.Bold)
|
||||
Text(radio?.gpsMessage ?: "Keep location permission enabled while driving.", color = Muted, fontSize = 12.sp, lineHeight = 19.sp)
|
||||
radio?.gpsAccuracyMeters?.let { Text("Accuracy ${it.round(0)} m", color = Accent, fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 10.dp)) }
|
||||
Text("${radio?.mappedSightings ?: 0} mapped points · ${radio?.sightings ?: 0} total sightings", color = Muted, fontSize = 11.sp, modifier = Modifier.padding(top = 8.dp))
|
||||
Text("Kismet · ${if (radio?.kismetAvailable == true) "connected" else "unavailable"}", color = if (radio?.kismetAvailable == true) Accent else Danger, fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 12.dp))
|
||||
Text(radio?.kismetMessage ?: "Start a session to connect to Kismet.", color = Muted, fontSize = 11.sp, lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Text("RECENT DEVICES", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp)
|
||||
if (radio?.devices.isNullOrEmpty()) MetricCard("No devices yet", "—", "Start a session to see Kismet observations")
|
||||
else radio!!.devices.forEach { device ->
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Surface), shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
Row(Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (device.technology == "bluetooth") "⌁" else "◌", color = if (device.technology == "bluetooth") Color(0xFF8BC4FF) else Accent, fontSize = 24.sp)
|
||||
Column(Modifier.weight(1f).padding(start = 12.dp)) { Text(device.label, color = Text, fontWeight = FontWeight.Bold, maxLines = 1); Text(device.macAddress ?: "Address unavailable", color = Muted, fontSize = 11.sp, maxLines = 1) }
|
||||
Text(device.channel ?: "—", color = Muted, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Text("RECENT MAP POINTS", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp, modifier = Modifier.padding(top = 6.dp))
|
||||
if (radio?.mappedPoints.isNullOrEmpty()) MetricCard("No mapped points yet", "—", "A fresh phone GPS fix will place observations here")
|
||||
else radio!!.mappedPoints.take(5).forEach { point ->
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Surface), shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
Row(Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (point.technology == "bluetooth") "⌁" else "◌", color = if (point.technology == "bluetooth") Color(0xFF8BC4FF) else Accent, fontSize = 24.sp)
|
||||
Column(Modifier.weight(1f).padding(start = 12.dp)) { Text(point.label, color = Text, fontWeight = FontWeight.Bold, maxLines = 1); Text("${point.latitude.formatCoordinate()}, ${point.longitude.formatCoordinate()}", color = Muted, fontSize = 11.sp) }
|
||||
Text(point.technology.uppercase(), color = Muted, fontSize = 10.sp, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item { Text("WiFi capture is passive; Bluetooth uses discoverable-device metadata scanning. No packet payloads, passwords, pairing, or service enumeration are collected.", color = Muted, fontSize = 11.sp, lineHeight = 17.sp, modifier = Modifier.padding(top = 4.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun Double.formatCoordinate() = String.format(Locale.US, "%.5f", this)
|
||||
|
||||
@Composable private fun ControlsScreen(state: CompanionUiState, launch: (Shortcut) -> Unit, forget: () -> Unit) {
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp), contentPadding = PaddingValues(bottom = 20.dp)) {
|
||||
item { Text("ADB SHORTCUTS", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.5.sp) }
|
||||
|
||||
@@ -21,12 +21,36 @@ data class CarSummary(
|
||||
val averageSpeedKph: Double?,
|
||||
val peakSpeedKph: Double?
|
||||
)
|
||||
data class Snapshot(val collectedAt: String, val system: SystemSummary, val car: CarSummary, val shortcuts: List<Shortcut>)
|
||||
data class WardrivingDevice(
|
||||
val technology: String,
|
||||
val label: String,
|
||||
val macAddress: String?,
|
||||
val channel: String?,
|
||||
val lastSeenAt: String
|
||||
)
|
||||
data class WardrivingPoint(val latitude: Double, val longitude: Double, val technology: String, val label: String, val observedAt: String)
|
||||
data class WardrivingSummary(
|
||||
val enabled: Boolean,
|
||||
val running: Boolean,
|
||||
val kismetAvailable: Boolean,
|
||||
val kismetMessage: String,
|
||||
val gpsAvailable: Boolean,
|
||||
val gpsAccuracyMeters: Double?,
|
||||
val gpsMessage: String,
|
||||
val wifiDevices: Int,
|
||||
val bluetoothDevices: Int,
|
||||
val sightings: Int,
|
||||
val mappedSightings: Int,
|
||||
val devices: List<WardrivingDevice>,
|
||||
val mappedPoints: List<WardrivingPoint>
|
||||
)
|
||||
data class Snapshot(val collectedAt: String, val system: SystemSummary, val car: CarSummary, val shortcuts: List<Shortcut>, val wardriving: WardrivingSummary)
|
||||
enum class ConnectionState { STOPPED, SCANNING, CONNECTING, CONNECTED, DISCONNECTED }
|
||||
data class CompanionUiState(
|
||||
val connection: ConnectionState = ConnectionState.STOPPED,
|
||||
val paired: Boolean = false,
|
||||
val snapshot: Snapshot? = null,
|
||||
val error: String? = null,
|
||||
val busyShortcut: Int? = null
|
||||
val busyShortcut: Int? = null,
|
||||
val busyWardriving: Boolean = false
|
||||
)
|
||||
Binary file not shown.
+70
-1
@@ -65,7 +65,44 @@ apt-get install -y \
|
||||
wireless-regdb \
|
||||
wpasupplicant
|
||||
|
||||
for required_command in conntrack dnsmasq ip journalctl nmcli nft rfkill uuidgen wpa_passphrase; do
|
||||
install_kismet_packages() {
|
||||
local packages=(kismet kismet-capture-linux-wifi kismet-capture-linux-bluetooth kismet-logtools)
|
||||
if apt-cache show kismet >/dev/null 2>&1 && apt-cache show kismet-capture-linux-wifi >/dev/null 2>&1 && apt-cache show kismet-capture-linux-bluetooth >/dev/null 2>&1 && apt-cache show kismet-logtools >/dev/null 2>&1; then
|
||||
apt-get install -y "${packages[@]}"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "Kismet is not available in the configured Debian repositories; adding the Kismet package repository."
|
||||
install -d -m 0755 /etc/apt/keyrings
|
||||
local key_tmp
|
||||
key_tmp="$(mktemp)"
|
||||
curl --fail --silent --show-error --location 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x5345B8BF43403B93&options=armor' --output "${key_tmp}"
|
||||
if ! gpg --show-keys --with-colons "${key_tmp}" | grep -q 'fpr:::::::::ADA09A0E9B80ACCCE8FE6BB65345B8BF43403B93:'; then
|
||||
echo "The Kismet repository signing key fingerprint did not match the expected value." >&2
|
||||
exit 1
|
||||
fi
|
||||
gpg --dearmor --yes --output /etc/apt/keyrings/kismet-archive-keyring.gpg "${key_tmp}"
|
||||
rm -f -- "${key_tmp}"
|
||||
chmod 0644 /etc/apt/keyrings/kismet-archive-keyring.gpg
|
||||
local codename="${VERSION_CODENAME:-}"
|
||||
if [[ -z "${codename}" ]]; then
|
||||
codename="$(. /etc/os-release && printf '%s' "${VERSION_CODENAME:-bookworm}")"
|
||||
fi
|
||||
printf 'deb [arch=%s signed-by=/etc/apt/keyrings/kismet-archive-keyring.gpg] https://www.kismetwireless.net/repos/apt/release/%s %s main\n' \
|
||||
"$(dpkg --print-architecture)" "${codename}" "${codename}" > /etc/apt/sources.list.d/kismet.list
|
||||
apt-get update
|
||||
for package in "${packages[@]}"; do
|
||||
if ! apt-cache policy "${package}" | awk '$1 == "Candidate:" && $2 != "(none)" { found = 1 } END { exit found ? 0 : 1 }'; then
|
||||
echo "The Kismet repository has no ${package} build for $(dpkg --print-architecture)/${codename}. Use a 64-bit Raspberry Pi OS image or a supported Debian release." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
apt-get install -y "${packages[@]}"
|
||||
}
|
||||
|
||||
install_kismet_packages
|
||||
|
||||
for required_command in conntrack dnsmasq ip journalctl kismet kismet_cap_linux_bluetooth kismet_cap_linux_wifi nmcli nft rfkill uuidgen wpa_passphrase; do
|
||||
if ! command -v "${required_command}" >/dev/null 2>&1; then
|
||||
echo "Required network command was not installed: ${required_command}" >&2
|
||||
exit 1
|
||||
@@ -98,6 +135,18 @@ fi
|
||||
if getent group plugdev >/dev/null 2>&1; then
|
||||
usermod --append --groups plugdev "${SERVICE_USER}"
|
||||
fi
|
||||
if ! getent group kismet >/dev/null 2>&1; then
|
||||
groupadd --system kismet
|
||||
fi
|
||||
if ! getent group netdev >/dev/null 2>&1; then
|
||||
groupadd --system netdev
|
||||
fi
|
||||
if ! id kismet >/dev/null 2>&1; then
|
||||
useradd --system --no-create-home --shell /usr/sbin/nologin --gid kismet kismet
|
||||
fi
|
||||
if getent group netdev >/dev/null 2>&1; then
|
||||
usermod --append --groups netdev kismet
|
||||
fi
|
||||
install -d -m 0755 -o root -g root "${INSTALL_ROOT}" "${REPOSITORY}" "${RELEASES}"
|
||||
install -d -m 0750 -o "${SERVICE_USER}" -g "${SERVICE_USER}" "${DATA_DIR}"
|
||||
install -d -m 0750 -o root -g "${SERVICE_USER}" "${CONFIG_DIR}"
|
||||
@@ -145,6 +194,7 @@ echo "[5/7] Installing system services"
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-network-setup" /usr/local/sbin/pi-car-companion-network-setup
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-power" /usr/local/sbin/pi-car-companion-power
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-bluetooth-control" /usr/local/sbin/pi-car-companion-bluetooth-control
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-wardriving-control" /usr/local/sbin/pi-car-companion-wardriving-control
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-update" /usr/local/sbin/pi-car-companion-update
|
||||
install -d -m 0755 /usr/local/libexec
|
||||
install -m 0755 "${SCRIPT_DIR}/scripts/pi-car-companion-bluetooth" /usr/local/libexec/pi-car-companion-bluetooth
|
||||
@@ -155,6 +205,7 @@ install -m 0644 "${SCRIPT_DIR}/systemd/pi-car-companion-network.service" /etc/sy
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/pi-car-companion-network-configure.service" /etc/systemd/system/pi-car-companion-network-configure.service
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/pi-car-companion-network-observer.service" /etc/systemd/system/pi-car-companion-network-observer.service
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/pi-car-companion-bluetooth.service" /etc/systemd/system/pi-car-companion-bluetooth.service
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/pi-car-companion-kismet.service" /etc/systemd/system/pi-car-companion-kismet.service
|
||||
install -m 0440 "${SCRIPT_DIR}/systemd/pi-car-companion.sudoers" /etc/sudoers.d/pi-car-companion
|
||||
visudo -cf /etc/sudoers.d/pi-car-companion >/dev/null
|
||||
install -d -m 0755 /etc/avahi/services
|
||||
@@ -188,6 +239,14 @@ NETWORK_HOTSPOT_CONNECTION=pi-car-hotspot
|
||||
NETWORK_PROBE_TIMEOUT_SECONDS=60
|
||||
NETWORK_STABILITY_SECONDS=10
|
||||
NETWORK_POLL_SECONDS=5
|
||||
WARDRIVING_ENABLED=true
|
||||
WARDRIVING_STATUS_PATH=${DATA_DIR}/wardriving-status.json
|
||||
WARDRIVING_KISMET_URL=http://127.0.0.1:2501
|
||||
WARDRIVING_KISMET_AUTH_PATH=${DATA_DIR}/kismet/kismet-api-credentials.json
|
||||
WARDRIVING_POLL_SECONDS=5
|
||||
WARDRIVING_MAX_SIGHTINGS=250000
|
||||
WARDRIVING_WIFI_INTERFACE=
|
||||
WARDRIVING_BLUETOOTH_INTERFACE=hci0
|
||||
EOF
|
||||
fi
|
||||
|
||||
@@ -209,6 +268,14 @@ ensure_env_default NETWORK_HOTSPOT_CONNECTION pi-car-hotspot
|
||||
ensure_env_default NETWORK_PROBE_TIMEOUT_SECONDS 60
|
||||
ensure_env_default NETWORK_STABILITY_SECONDS 10
|
||||
ensure_env_default NETWORK_POLL_SECONDS 5
|
||||
ensure_env_default WARDRIVING_ENABLED true
|
||||
ensure_env_default WARDRIVING_STATUS_PATH "${DATA_DIR}/wardriving-status.json"
|
||||
ensure_env_default WARDRIVING_KISMET_URL http://127.0.0.1:2501
|
||||
ensure_env_default WARDRIVING_KISMET_AUTH_PATH "${DATA_DIR}/kismet/kismet-api-credentials.json"
|
||||
ensure_env_default WARDRIVING_POLL_SECONDS 5
|
||||
ensure_env_default WARDRIVING_MAX_SIGHTINGS 250000
|
||||
ensure_env_default WARDRIVING_WIFI_INTERFACE ""
|
||||
ensure_env_default WARDRIVING_BLUETOOTH_INTERFACE hci0
|
||||
chown root:"${SERVICE_USER}" "${CONFIG_DIR}/companion.env"
|
||||
chmod 0640 "${CONFIG_DIR}/companion.env"
|
||||
|
||||
@@ -224,6 +291,8 @@ systemctl enable --now avahi-daemon
|
||||
systemctl enable pi-car-companion.service
|
||||
systemctl enable --now bluetooth.service
|
||||
systemctl enable pi-car-companion-bluetooth.service
|
||||
systemctl disable --now kismet.service >/dev/null 2>&1 || true
|
||||
systemctl disable --now pi-car-companion-kismet.service >/dev/null 2>&1 || true
|
||||
systemctl enable pi-car-companion-network-observer.service
|
||||
if grep -qx 'NETWORK_MANAGER_ENABLED=true' "${CONFIG_DIR}/companion.env"; then
|
||||
systemctl enable --now pi-car-companion-network.service
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@
|
||||
"test": "npm run test --workspaces --if-present",
|
||||
"build": "npm run build --workspaces --if-present",
|
||||
"build:apk": "./build-apk.sh",
|
||||
"check:scripts": "bash -n install.sh build-apk.sh scripts/pi-car-companion-update scripts/pi-car-companion-network-setup scripts/pi-car-companion-power scripts/pi-car-companion-bluetooth-control && python3 -c \"compile(open('scripts/pi-car-companion-bluetooth', encoding='utf-8').read(), 'scripts/pi-car-companion-bluetooth', 'exec')\"",
|
||||
"check:scripts": "bash -n install.sh build-apk.sh scripts/pi-car-companion-update scripts/pi-car-companion-network-setup scripts/pi-car-companion-power scripts/pi-car-companion-bluetooth-control scripts/pi-car-companion-wardriving-control && python3 -c \"compile(open('scripts/pi-car-companion-bluetooth', encoding='utf-8').read(), 'scripts/pi-car-companion-bluetooth', 'exec')\"",
|
||||
"check": "npm run check:scripts && npm run lint && npm run typecheck && npm test && npm run build"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -194,6 +194,11 @@ def route_operation(operation, payload):
|
||||
return "GET", "/internal/mobile/snapshot", None
|
||||
if operation == "location":
|
||||
return "POST", "/internal/mobile/location", payload
|
||||
if operation == "wardriving":
|
||||
action = payload.get("action")
|
||||
if action not in ("start", "stop", "restart"):
|
||||
raise ProtocolError("INVALID_WARDRIVING_ACTION", "Wardriving action was invalid")
|
||||
return "POST", "/internal/mobile/wardriving", {"action": action}
|
||||
if operation == "launchShortcut":
|
||||
shortcut_id = payload.get("id")
|
||||
if not isinstance(shortcut_id, int) or shortcut_id < 1:
|
||||
|
||||
@@ -69,6 +69,9 @@ install_integration_files() {
|
||||
if [[ -f "${source_release}/scripts/pi-car-companion-bluetooth-control" ]]; then
|
||||
install -m 0755 "${source_release}/scripts/pi-car-companion-bluetooth-control" /usr/local/sbin/pi-car-companion-bluetooth-control
|
||||
fi
|
||||
if [[ -f "${source_release}/scripts/pi-car-companion-wardriving-control" ]]; then
|
||||
install -m 0755 "${source_release}/scripts/pi-car-companion-wardriving-control" /usr/local/sbin/pi-car-companion-wardriving-control
|
||||
fi
|
||||
install -d -m 0755 /usr/local/libexec
|
||||
install -m 0755 "${source_release}/scripts/pi-car-companion-bluetooth" /usr/local/libexec/pi-car-companion-bluetooth
|
||||
install -m 0644 "${source_release}/systemd/pi-car-companion.service" /etc/systemd/system/pi-car-companion.service
|
||||
@@ -78,6 +81,9 @@ install_integration_files() {
|
||||
install -m 0644 "${source_release}/systemd/pi-car-companion-network-configure.service" /etc/systemd/system/pi-car-companion-network-configure.service
|
||||
install -m 0644 "${source_release}/systemd/pi-car-companion-network-observer.service" /etc/systemd/system/pi-car-companion-network-observer.service
|
||||
install -m 0644 "${source_release}/systemd/pi-car-companion-bluetooth.service" /etc/systemd/system/pi-car-companion-bluetooth.service
|
||||
if [[ -f "${source_release}/systemd/pi-car-companion-kismet.service" ]]; then
|
||||
install -m 0644 "${source_release}/systemd/pi-car-companion-kismet.service" /etc/systemd/system/pi-car-companion-kismet.service
|
||||
fi
|
||||
install -m 0440 "${source_release}/systemd/pi-car-companion.sudoers" /etc/sudoers.d/pi-car-companion
|
||||
install -d -m 0755 /etc/NetworkManager/dnsmasq-shared.d
|
||||
install -m 0644 "${source_release}/config/dnsmasq-shared-pi-car-companion.conf" /etc/NetworkManager/dnsmasq-shared.d/pi-car-companion.conf
|
||||
@@ -135,6 +141,7 @@ if [[ -n "${FROM_REVISION}" && "${FROM_REVISION}" == "${TO_REVISION}" ]]; then
|
||||
install_integration_files "${CURRENT}"
|
||||
visudo -cf /etc/sudoers.d/pi-car-companion >/dev/null
|
||||
systemctl daemon-reload
|
||||
systemctl disable --now kismet.service >/dev/null 2>&1 || true
|
||||
fi
|
||||
write_status "current" "Pi Car Companion is already up to date."
|
||||
exit 0
|
||||
@@ -176,6 +183,7 @@ chown -R root:root "${release_final}"
|
||||
install_integration_files "${release_final}"
|
||||
visudo -cf /etc/sudoers.d/pi-car-companion >/dev/null
|
||||
systemctl daemon-reload
|
||||
systemctl disable --now kismet.service >/dev/null 2>&1 || true
|
||||
|
||||
ln -sfn "releases/${TO_REVISION}" "${INSTALL_ROOT}/current.next"
|
||||
mv -Tf "${INSTALL_ROOT}/current.next" "${CURRENT}"
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
if [[ ${EUID} -ne 0 ]]; then
|
||||
echo "The wardriving control helper must run as root." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ACTION="${1:-}"
|
||||
case "${ACTION}" in
|
||||
start|stop|restart) ;;
|
||||
*)
|
||||
echo "Usage: pi-car-companion-wardriving-control start|stop|restart" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
ENV_FILE=/etc/pi-car-companion/companion.env
|
||||
SERVICE=pi-car-companion-kismet.service
|
||||
CONFIG=/etc/kismet/kismet_site.conf
|
||||
DATA_DIR=/var/lib/pi-car-companion/kismet
|
||||
|
||||
if [[ -f "${ENV_FILE}" ]]; then
|
||||
# shellcheck disable=SC1091
|
||||
source "${ENV_FILE}"
|
||||
fi
|
||||
|
||||
AUTH_PATH="${WARDRIVING_KISMET_AUTH_PATH:-${DATA_DIR}/kismet-api-credentials.json}"
|
||||
|
||||
wifi_interface="${WARDRIVING_WIFI_INTERFACE:-}"
|
||||
bluetooth_interface="${WARDRIVING_BLUETOOTH_INTERFACE-hci0}"
|
||||
hotspot_interface="${NETWORK_HOTSPOT_INTERFACE:-wlan0}"
|
||||
upstream_interface="${NETWORK_UPSTREAM_INTERFACE:-wlan1}"
|
||||
if [[ -z "${wifi_interface}" ]]; then
|
||||
wifi_interface="$(nmcli -t -f DEVICE,TYPE device 2>/dev/null | awk -F: -v hotspot="${hotspot_interface}" -v upstream="${upstream_interface}" '$2 == "wifi" && $1 != hotspot && $1 != upstream { print $1; exit }')"
|
||||
fi
|
||||
|
||||
if [[ -n "${wifi_interface}" && ! "${wifi_interface}" =~ ^[a-zA-Z0-9._-]{1,64}$ ]] || [[ -n "${bluetooth_interface}" && ! "${bluetooth_interface}" =~ ^[a-zA-Z0-9._-]{1,64}$ ]]; then
|
||||
echo "Wardriving interfaces contain unsupported characters." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -n "${wifi_interface}" && ( "${wifi_interface}" == "${hotspot_interface}" || "${wifi_interface}" == "${upstream_interface}" ) ]]; then
|
||||
echo "Wardriving cannot use the hotspot or upstream WiFi interface (${wifi_interface})." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
write_config() {
|
||||
install -d -m 0750 -o root -g pi-companion "${DATA_DIR}" "${DATA_DIR}/config" "${DATA_DIR}/config/httpd" /etc/kismet
|
||||
local username="pi-car-companion"
|
||||
local password=""
|
||||
if [[ -f "${AUTH_PATH}" ]]; then
|
||||
password="$(sed -n 's/.*"password"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "${AUTH_PATH}" | head -n 1)"
|
||||
fi
|
||||
if [[ -z "${password}" ]]; then
|
||||
password="$(uuidgen | tr -d '-')$(uuidgen | tr -d '-')"
|
||||
fi
|
||||
install -d -m 0750 -o root -g pi-companion "$(dirname -- "${AUTH_PATH}")"
|
||||
printf '{"username":"%s","password":"%s"}\n' "${username}" "${password}" > "${AUTH_PATH}"
|
||||
chmod 0640 "${AUTH_PATH}"
|
||||
chown root:pi-companion "${AUTH_PATH}"
|
||||
local auth_config="${DATA_DIR}/config/kismet_httpd.conf"
|
||||
printf 'httpd_username=%s\nhttpd_password=%s\n' "${username}" "${password}" > "${auth_config}"
|
||||
chmod 0600 "${auth_config}"
|
||||
chown root:root "${auth_config}"
|
||||
local temporary="${CONFIG}.tmp"
|
||||
cat > "${temporary}" <<EOF
|
||||
# Generated by Pi Car Companion. WiFi is passive; Bluetooth uses discoverable metadata scanning.
|
||||
configdir=${DATA_DIR}/config
|
||||
httpd_auth_file=${auth_config}
|
||||
httpd_session_db=${DATA_DIR}/config/session.db
|
||||
httpd_user_home=${DATA_DIR}/config/httpd
|
||||
log_prefix=${DATA_DIR}
|
||||
# Keep Kismet's live device index available to the API without retaining raw
|
||||
# packet payloads on disk. Pi Car Companion stores the bounded sightings table.
|
||||
log_types=kismet
|
||||
kis_log_packets=false
|
||||
kis_log_ephemeral_dangerous=true
|
||||
server_name=pi-car-companion
|
||||
httpd_bind_address=127.0.0.1
|
||||
hidedata=true
|
||||
source=${wifi_interface}:name=car-wifi
|
||||
EOF
|
||||
if [[ -z "${wifi_interface}" ]]; then
|
||||
sed -i '/^source=:name=car-wifi$/d' "${temporary}"
|
||||
fi
|
||||
if [[ -n "${bluetooth_interface}" ]]; then
|
||||
printf 'source=%s:name=car-bluetooth\n' "${bluetooth_interface}" >> "${temporary}"
|
||||
fi
|
||||
chmod 0600 "${temporary}"
|
||||
mv -f -- "${temporary}" "${CONFIG}"
|
||||
chown root:kismet "${CONFIG}"
|
||||
}
|
||||
|
||||
stop_bluetooth_discovery() {
|
||||
if [[ -z "${bluetooth_interface}" || ! "${bluetooth_interface}" =~ ^hci[0-9]+$ ]] || ! command -v btmgmt >/dev/null 2>&1; then
|
||||
return
|
||||
fi
|
||||
btmgmt --index "${bluetooth_interface#hci}" stop-discovery >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
case "${ACTION}" in
|
||||
start)
|
||||
write_config
|
||||
systemctl start "${SERVICE}"
|
||||
;;
|
||||
stop)
|
||||
systemctl stop "${SERVICE}"
|
||||
stop_bluetooth_discovery
|
||||
;;
|
||||
restart)
|
||||
write_config
|
||||
systemctl restart "${SERVICE}"
|
||||
;;
|
||||
esac
|
||||
+73
-1
@@ -38,6 +38,7 @@ import {
|
||||
import { CarTelemetryRecorder, type TelemetryPeriod } from "./car-telemetry.js";
|
||||
import { openShell } from "./shell.js";
|
||||
import { systemPowerActionSchema, triggerSystemPower } from "./system.js";
|
||||
import { WardrivingRecorder, wardrivingActionSchema, wardrivingClearSchema } from "./wardriving.js";
|
||||
import { isLoopbackAddress, registerMobileRoutes } from "./mobile.js";
|
||||
import "./types.js";
|
||||
|
||||
@@ -142,8 +143,10 @@ export async function buildApp(config: AppConfig): Promise<FastifyInstance> {
|
||||
const database = openDatabase(config.databasePath);
|
||||
const jobRunner = new JobRunner(database, undefined, config.adb);
|
||||
const carTelemetry = new CarTelemetryRecorder(database, config.adb);
|
||||
const wardriving = new WardrivingRecorder(database, config);
|
||||
if (config.adb.enabled) void collectAdbStatus(config.adb);
|
||||
carTelemetry.start();
|
||||
wardriving.start();
|
||||
|
||||
app.decorate("database", database);
|
||||
app.decorate("jobRunner", jobRunner);
|
||||
@@ -159,6 +162,7 @@ export async function buildApp(config: AppConfig): Promise<FastifyInstance> {
|
||||
|
||||
app.addHook("onClose", async () => {
|
||||
carTelemetry.stop();
|
||||
wardriving.stop();
|
||||
jobRunner.close();
|
||||
database.close();
|
||||
});
|
||||
@@ -327,7 +331,7 @@ export async function buildApp(config: AppConfig): Promise<FastifyInstance> {
|
||||
return { loggedOut: true };
|
||||
});
|
||||
|
||||
registerMobileRoutes(app, database, config.adb, carTelemetry, requireUser);
|
||||
registerMobileRoutes(app, database, config.adb, carTelemetry, wardriving, requireUser);
|
||||
|
||||
app.get("/api/status", async (request, reply) => {
|
||||
if (!requireUser(request, reply)) return;
|
||||
@@ -377,6 +381,74 @@ export async function buildApp(config: AppConfig): Promise<FastifyInstance> {
|
||||
return readNetworkActivity(config.network.activityPath);
|
||||
});
|
||||
|
||||
app.get("/api/wardriving", async (request, reply) => {
|
||||
if (!requireUser(request, reply)) return;
|
||||
return wardriving.snapshot();
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/wardriving/actions",
|
||||
{ config: { rateLimit: { max: 12, timeWindow: "10 minutes" } } },
|
||||
async (request, reply) => {
|
||||
if (!requireUser(request, reply)) return;
|
||||
const parsed = z.object({ action: wardrivingActionSchema }).safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: "INVALID_WARDRIVING_ACTION", message: "That wardriving action is not available" } });
|
||||
}
|
||||
try {
|
||||
const snapshot = await wardriving.action(parsed.data.action, request.authUser!.id);
|
||||
audit(database, {
|
||||
actorUserId: request.authUser!.id,
|
||||
action: `wardriving.${parsed.data.action}`,
|
||||
result: "success",
|
||||
ipAddress: clientAddress(request)
|
||||
});
|
||||
return snapshot;
|
||||
} catch (error) {
|
||||
audit(database, {
|
||||
actorUserId: request.authUser!.id,
|
||||
action: `wardriving.${parsed.data.action}`,
|
||||
result: "failure",
|
||||
ipAddress: clientAddress(request),
|
||||
details: { reason: error instanceof Error ? error.message : "control_failed" }
|
||||
});
|
||||
return reply.code(503).send({
|
||||
error: {
|
||||
code: error instanceof Error && error.message === "WARDRIVING_DISABLED" ? "WARDRIVING_DISABLED" : "WARDRIVING_CONTROL_FAILED",
|
||||
message: error instanceof Error && error.message === "WARDRIVING_DISABLED"
|
||||
? "Wardriving is not enabled in the Pi configuration"
|
||||
: "The Pi could not change the Kismet wardriving service"
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.post(
|
||||
"/api/wardriving/clear",
|
||||
{ config: { rateLimit: { max: 3, timeWindow: "10 minutes" } } },
|
||||
async (request, reply) => {
|
||||
if (!requireUser(request, reply)) return;
|
||||
const parsed = wardrivingClearSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: { code: "INVALID_WARDRIVING_CLEAR_MODE", message: "Choose which wardriving data to clear" } });
|
||||
}
|
||||
try {
|
||||
const result = wardriving.clear(parsed.data.mode);
|
||||
audit(database, {
|
||||
actorUserId: request.authUser!.id,
|
||||
action: "wardriving.clear",
|
||||
result: "success",
|
||||
ipAddress: clientAddress(request),
|
||||
details: result
|
||||
});
|
||||
return result;
|
||||
} catch {
|
||||
return reply.code(409).send({ error: { code: "WARDRIVING_SESSION_ACTIVE", message: "Stop the active wardriving session before clearing data" } });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.get("/api/adb/packages", async (request, reply) => {
|
||||
if (!requireUser(request, reply)) return;
|
||||
try {
|
||||
|
||||
@@ -22,6 +22,14 @@ const schema = z.object({
|
||||
NETWORK_COMMAND_PATH: z.string().default("/var/lib/pi-car-companion/network-command.json"),
|
||||
NETWORK_CONFIGURATION_REQUEST_PATH: z.string().default("/var/lib/pi-car-companion/network-configuration-request.json"),
|
||||
NETWORK_ACTIVITY_PATH: z.string().default("/var/lib/pi-car-companion/network-activity.json"),
|
||||
WARDRIVING_ENABLED: booleanFromString,
|
||||
WARDRIVING_STATUS_PATH: z.string().default("/var/lib/pi-car-companion/wardriving-status.json"),
|
||||
WARDRIVING_KISMET_URL: z.string().url().default("http://127.0.0.1:2501"),
|
||||
WARDRIVING_KISMET_AUTH_PATH: z.string().default("/var/lib/pi-car-companion/kismet/kismet-api-credentials.json"),
|
||||
WARDRIVING_POLL_SECONDS: z.coerce.number().int().min(2).max(60).default(5),
|
||||
WARDRIVING_MAX_SIGHTINGS: z.coerce.number().int().min(1_000).max(1_000_000).default(250_000),
|
||||
WARDRIVING_WIFI_INTERFACE: z.string().max(64).default(""),
|
||||
WARDRIVING_BLUETOOTH_INTERFACE: z.string().max(64).default("hci0"),
|
||||
ADB_ENABLED: booleanFromString,
|
||||
ADB_PATH: z.string().min(1).default("adb"),
|
||||
ADB_SERIAL: z.string().max(128).regex(/^[a-zA-Z0-9._:-]*$/).default(""),
|
||||
@@ -45,9 +53,34 @@ export type AppConfig = {
|
||||
configurationRequestPath: string;
|
||||
activityPath: string;
|
||||
};
|
||||
wardriving?: WardrivingConfig;
|
||||
adb: AdbConfig;
|
||||
};
|
||||
|
||||
export type WardrivingConfig = {
|
||||
enabled: boolean;
|
||||
statusPath: string;
|
||||
kismetUrl: string;
|
||||
authPath: string;
|
||||
pollSeconds: number;
|
||||
maxSightings: number;
|
||||
wifiInterface: string | null;
|
||||
bluetoothInterface: string | null;
|
||||
};
|
||||
|
||||
export function getWardrivingConfig(config: AppConfig): WardrivingConfig {
|
||||
return config.wardriving ?? {
|
||||
enabled: false,
|
||||
statusPath: "/var/lib/pi-car-companion/wardriving-status.json",
|
||||
kismetUrl: "http://127.0.0.1:2501",
|
||||
authPath: "/var/lib/pi-car-companion/kismet/kismet-api-credentials.json",
|
||||
pollSeconds: 5,
|
||||
maxSightings: 250_000,
|
||||
wifiInterface: null,
|
||||
bluetoothInterface: "hci0"
|
||||
};
|
||||
}
|
||||
|
||||
export function loadConfig(environment: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
const parsed = schema.parse(environment);
|
||||
const allowedOrigins = new Set(
|
||||
@@ -79,6 +112,16 @@ export function loadConfig(environment: NodeJS.ProcessEnv = process.env): AppCon
|
||||
configurationRequestPath: parsed.NETWORK_CONFIGURATION_REQUEST_PATH,
|
||||
activityPath: parsed.NETWORK_ACTIVITY_PATH
|
||||
},
|
||||
wardriving: {
|
||||
enabled: parsed.WARDRIVING_ENABLED,
|
||||
statusPath: parsed.WARDRIVING_STATUS_PATH,
|
||||
kismetUrl: parsed.WARDRIVING_KISMET_URL.replace(/\/$/, ""),
|
||||
authPath: parsed.WARDRIVING_KISMET_AUTH_PATH,
|
||||
pollSeconds: parsed.WARDRIVING_POLL_SECONDS,
|
||||
maxSightings: parsed.WARDRIVING_MAX_SIGHTINGS,
|
||||
wifiInterface: parsed.WARDRIVING_WIFI_INTERFACE.trim() || null,
|
||||
bluetoothInterface: parsed.WARDRIVING_BLUETOOTH_INTERFACE.trim() || null
|
||||
},
|
||||
adb: {
|
||||
enabled: parsed.ADB_ENABLED,
|
||||
executable: parsed.ADB_PATH,
|
||||
|
||||
@@ -147,6 +147,61 @@ function migrate(database: CompanionDatabase): void {
|
||||
|
||||
CREATE INDEX IF NOT EXISTS trip_points_trip_time_idx ON trip_points(trip_id, captured_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS wardriving_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
started_at TEXT NOT NULL,
|
||||
ended_at TEXT,
|
||||
state TEXT NOT NULL CHECK (state IN ('running', 'stopped', 'error')),
|
||||
wifi_interface TEXT,
|
||||
bluetooth_interface TEXT,
|
||||
started_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
stopped_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
error_message TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS wardriving_sessions_started_idx ON wardriving_sessions(started_at DESC);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS wardriving_active_session_idx
|
||||
ON wardriving_sessions(state) WHERE state = 'running';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS wardriving_devices (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kismet_key TEXT NOT NULL UNIQUE,
|
||||
technology TEXT NOT NULL CHECK (technology IN ('wifi', 'bluetooth', 'other')),
|
||||
mac_address TEXT,
|
||||
display_name TEXT,
|
||||
ssid TEXT,
|
||||
manufacturer TEXT,
|
||||
channel TEXT,
|
||||
encryption TEXT,
|
||||
first_seen_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
strongest_signal_dbm REAL,
|
||||
latest_latitude REAL,
|
||||
latest_longitude REAL,
|
||||
latest_accuracy_meters REAL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS wardriving_devices_technology_idx ON wardriving_devices(technology, last_seen_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS wardriving_devices_last_seen_idx ON wardriving_devices(last_seen_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS wardriving_sightings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL REFERENCES wardriving_sessions(id) ON DELETE CASCADE,
|
||||
device_id INTEGER NOT NULL REFERENCES wardriving_devices(id) ON DELETE CASCADE,
|
||||
observed_at TEXT NOT NULL,
|
||||
latitude REAL,
|
||||
longitude REAL,
|
||||
accuracy_meters REAL,
|
||||
signal_dbm REAL,
|
||||
channel TEXT,
|
||||
source TEXT NOT NULL,
|
||||
UNIQUE(session_id, device_id, observed_at, latitude, longitude)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS wardriving_sightings_session_time_idx ON wardriving_sightings(session_id, observed_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS wardriving_sightings_location_idx ON wardriving_sightings(latitude, longitude);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS car_telemetry_samples (
|
||||
recorded_at INTEGER PRIMARY KEY,
|
||||
speed_kph REAL,
|
||||
|
||||
+19
-1
@@ -9,6 +9,7 @@ import type { CompanionDatabase } from "./database.js";
|
||||
import { hashToken, randomToken } from "./security.js";
|
||||
import { collectSystemStatus } from "./status.js";
|
||||
import { TripStore } from "./trips.js";
|
||||
import type { WardrivingRecorder } from "./wardriving.js";
|
||||
|
||||
const pairingSchema = z.object({
|
||||
code: z.string().regex(/^\d{6}$/),
|
||||
@@ -70,6 +71,7 @@ export function registerMobileRoutes(
|
||||
database: CompanionDatabase,
|
||||
adbConfig: AdbConfig,
|
||||
carTelemetry: CarTelemetryRecorder,
|
||||
wardriving: WardrivingRecorder,
|
||||
requireWebUser: (request: FastifyRequest, reply: FastifyReply) => boolean
|
||||
): void {
|
||||
const trips = new TripStore(database);
|
||||
@@ -171,6 +173,7 @@ export function registerMobileRoutes(
|
||||
collectSystemStatus(adbConfig),
|
||||
carTelemetry.readLive().catch(() => null)
|
||||
]);
|
||||
const wardrivingSnapshot = await wardriving.snapshotForMobile();
|
||||
const shortcuts = database.prepare(
|
||||
"SELECT id, name, target_type AS type, target_value AS value FROM adb_shortcuts ORDER BY created_at, id"
|
||||
).all();
|
||||
@@ -180,7 +183,22 @@ export function registerMobileRoutes(
|
||||
bearing_degrees AS bearingDegrees, battery_percent AS batteryPercent, network_type AS networkType
|
||||
FROM mobile_phone_state WHERE device_id = ?`
|
||||
).get(device.id) ?? null;
|
||||
return { protocolVersion: 1, collectedAt: new Date().toISOString(), system, car, statistics: carTelemetry.store.overview(), shortcuts, phone };
|
||||
return { protocolVersion: 1, collectedAt: new Date().toISOString(), system, car, statistics: carTelemetry.store.overview(), shortcuts, phone, wardriving: wardrivingSnapshot };
|
||||
});
|
||||
|
||||
app.post("/internal/mobile/wardriving", async (request, reply) => {
|
||||
const device = authenticateMobile(database, request, reply);
|
||||
if (!device) return;
|
||||
const parsed = z.object({ action: z.enum(["start", "stop", "restart"]) }).safeParse(request.body);
|
||||
if (!parsed.success) return reply.code(400).send({ error: { code: "INVALID_WARDRIVING_ACTION", message: "That wardriving action is not available" } });
|
||||
try {
|
||||
const snapshot = await wardriving.action(parsed.data.action, null);
|
||||
auditMobile(database, device, `mobile.wardriving-${parsed.data.action}`, "success");
|
||||
return snapshot;
|
||||
} catch {
|
||||
auditMobile(database, device, `mobile.wardriving-${parsed.data.action}`, "failure");
|
||||
return reply.code(503).send({ error: { code: "WARDRIVING_CONTROL_FAILED", message: "The Pi could not change the wardriving session" } });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/internal/mobile/location", async (request, reply) => {
|
||||
|
||||
@@ -0,0 +1,662 @@
|
||||
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { z } from "zod";
|
||||
import type { AppConfig, WardrivingConfig } from "./config.js";
|
||||
import { getWardrivingConfig } from "./config.js";
|
||||
import type { CompanionDatabase } from "./database.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export const wardrivingActionSchema = z.enum(["start", "stop", "restart"]);
|
||||
export type WardrivingAction = z.infer<typeof wardrivingActionSchema>;
|
||||
export const wardrivingClearSchema = z.object({ mode: z.enum(["history", "all"]) });
|
||||
export type WardrivingClearMode = z.infer<typeof wardrivingClearSchema>["mode"];
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
type Technology = "wifi" | "bluetooth" | "other";
|
||||
|
||||
export type KismetDevice = {
|
||||
key: string;
|
||||
technology: Technology;
|
||||
macAddress: string | null;
|
||||
displayName: string | null;
|
||||
ssid: string | null;
|
||||
manufacturer: string | null;
|
||||
channel: string | null;
|
||||
encryption: string | null;
|
||||
firstSeenAt: string;
|
||||
lastSeenAt: string;
|
||||
signalDbm: number | null;
|
||||
};
|
||||
|
||||
type GpsFix = {
|
||||
receivedAt: string;
|
||||
capturedAt: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
accuracyMeters: number;
|
||||
ageSeconds: number;
|
||||
};
|
||||
|
||||
type KismetStatus = {
|
||||
available: boolean;
|
||||
running: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
};
|
||||
|
||||
type SessionRow = {
|
||||
id: number;
|
||||
startedAt: string;
|
||||
endedAt: string | null;
|
||||
state: "running" | "stopped" | "error";
|
||||
wifiInterface: string | null;
|
||||
bluetoothInterface: string | null;
|
||||
errorMessage: string | null;
|
||||
};
|
||||
|
||||
export type WardrivingSnapshot = {
|
||||
supported: boolean;
|
||||
enabled: boolean;
|
||||
updatedAt: string;
|
||||
running: boolean;
|
||||
kismet: KismetStatus;
|
||||
session: (SessionRow & { devices: number; sightings: number }) | null;
|
||||
gps: { available: boolean; fix: GpsFix | null; message: string };
|
||||
sources: {
|
||||
wifiInterface: string | null;
|
||||
bluetoothInterface: string | null;
|
||||
wifiPassive: true;
|
||||
bluetoothMode: "discoverable-metadata";
|
||||
noPairing: true;
|
||||
};
|
||||
statistics: {
|
||||
devices: number;
|
||||
wifiDevices: number;
|
||||
bluetoothDevices: number;
|
||||
sightings: number;
|
||||
mappedSightings: number;
|
||||
sessions: number;
|
||||
lastSeenAt: string | null;
|
||||
};
|
||||
devices: Array<{
|
||||
id: number;
|
||||
key: string;
|
||||
technology: Technology;
|
||||
macAddress: string | null;
|
||||
displayName: string | null;
|
||||
ssid: string | null;
|
||||
manufacturer: string | null;
|
||||
channel: string | null;
|
||||
encryption: string | null;
|
||||
firstSeenAt: string;
|
||||
lastSeenAt: string;
|
||||
strongestSignalDbm: number | null;
|
||||
latestLatitude: number | null;
|
||||
latestLongitude: number | null;
|
||||
latestAccuracyMeters: number | null;
|
||||
}>;
|
||||
sightings: Array<{
|
||||
id: number;
|
||||
sessionId: number;
|
||||
deviceId: number;
|
||||
observedAt: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
accuracyMeters: number | null;
|
||||
signalDbm: number | null;
|
||||
channel: string | null;
|
||||
source: string;
|
||||
technology: Technology;
|
||||
displayName: string | null;
|
||||
macAddress: string | null;
|
||||
}>;
|
||||
recentSessions: Array<SessionRow & { devices: number; sightings: number }>;
|
||||
};
|
||||
|
||||
type Observation = KismetDevice & { observedAt: string; source: string };
|
||||
|
||||
function asRecord(value: unknown): JsonRecord | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as JsonRecord : null;
|
||||
}
|
||||
|
||||
function firstValue(record: JsonRecord, ...keys: string[]): unknown {
|
||||
for (const key of keys) {
|
||||
if (key in record && record[key] !== null && record[key] !== undefined) return record[key];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function nestedValue(record: JsonRecord, keys: string[], skipEmptyStrings = false): unknown {
|
||||
const usable = (value: unknown): boolean => value !== null && value !== undefined && (!skipEmptyStrings || value !== "");
|
||||
const wanted = new Set(keys);
|
||||
const pending: Array<{ value: unknown; depth: number }> = [{ value: record, depth: 0 }];
|
||||
const visited = new Set<object>();
|
||||
while (pending.length > 0) {
|
||||
const item = pending.shift()!;
|
||||
const current = asRecord(item.value);
|
||||
if (!current || visited.has(current) || item.depth > 8) continue;
|
||||
visited.add(current);
|
||||
for (const key of keys) {
|
||||
if (key in current && usable(current[key])) return current[key];
|
||||
}
|
||||
for (const [key, value] of Object.entries(current)) {
|
||||
if (usable(value) && [...wanted].some((candidate) => key === candidate || key.endsWith(`.${candidate}`))) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(current)) {
|
||||
if (asRecord(value)) pending.push({ value, depth: item.depth + 1 });
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function stringFrom(value: unknown): string | null {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
||||
const nested = asRecord(value);
|
||||
if (!nested) return null;
|
||||
const candidate = nestedValue(nested, ["value", "name", "ssid", "kismet.common.ssid.ssid", "dot11.advertisedssid.ssid"], true);
|
||||
return candidate === undefined ? null : stringFrom(candidate);
|
||||
}
|
||||
|
||||
function stringValue(record: JsonRecord, ...keys: string[]): string | null {
|
||||
return stringFrom(firstValue(record, ...keys)) ?? stringFrom(nestedValue(record, keys, true));
|
||||
}
|
||||
|
||||
function numberFrom(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);
|
||||
const nested = asRecord(value);
|
||||
if (!nested) return null;
|
||||
const candidate = nestedValue(nested, [
|
||||
"value",
|
||||
"last_signal",
|
||||
"signal",
|
||||
"dbm",
|
||||
"rssi",
|
||||
"kismet.common.signal.last_signal",
|
||||
"kismet.common.signal.last_signal_dbm"
|
||||
]);
|
||||
return candidate === undefined ? null : numberFrom(candidate);
|
||||
}
|
||||
|
||||
function numberValue(record: JsonRecord, ...keys: string[]): number | null {
|
||||
return numberFrom(firstValue(record, ...keys) ?? nestedValue(record, keys));
|
||||
}
|
||||
|
||||
function timestampValue(value: unknown, fallback: string): string {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
const milliseconds = value > 100_000_000_000 ? value : value * 1_000;
|
||||
const date = new Date(milliseconds);
|
||||
if (!Number.isNaN(date.getTime())) return date.toISOString();
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const numeric = Number(value);
|
||||
if (Number.isFinite(numeric)) return timestampValue(numeric, fallback);
|
||||
const date = new Date(value);
|
||||
if (!Number.isNaN(date.getTime())) return date.toISOString();
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function classify(record: JsonRecord): Technology {
|
||||
const type = `${stringValue(record, "kismet.device.base.type", "type", "kismet.device.base.phyname") ?? ""} ${stringValue(record, "kismet.device.base.name", "name") ?? ""}`.toLowerCase();
|
||||
if (type.includes("bluetooth") || type.includes("btbb") || type.includes("ble") || type.includes("btle")) return "bluetooth";
|
||||
if (type.includes("wi-fi") || type.includes("wifi") || type.includes("802.11") || type.includes("access point")) return "wifi";
|
||||
return "other";
|
||||
}
|
||||
|
||||
function deviceRecords(payload: unknown): JsonRecord[] {
|
||||
if (Array.isArray(payload)) return payload.map(asRecord).filter((item): item is JsonRecord => item !== null);
|
||||
const record = asRecord(payload);
|
||||
if (!record) return [];
|
||||
for (const key of ["devices", "results", "data", "kismet.devices"]) {
|
||||
const nested = record[key];
|
||||
if (Array.isArray(nested)) return nested.map(asRecord).filter((item): item is JsonRecord => item !== null);
|
||||
}
|
||||
const values = Object.values(record).map(asRecord).filter((item): item is JsonRecord => item !== null);
|
||||
return values.length > 0 ? values : [record];
|
||||
}
|
||||
|
||||
export function normalizeKismetDevice(record: JsonRecord, now: string): KismetDevice | null {
|
||||
const key = stringValue(record, "kismet.device.base.key", "key", "kismet.device.base.macaddr", "macaddr", "mac")
|
||||
?.toLowerCase();
|
||||
if (!key) return null;
|
||||
const macAddress = stringValue(record, "kismet.device.base.macaddr", "macaddr", "mac")?.toUpperCase() ?? null;
|
||||
const ssid = stringValue(
|
||||
record,
|
||||
"kismet.device.base.ssid",
|
||||
"ssid",
|
||||
"kismet.common.ssid.ssid",
|
||||
"dot11.device.last_beaconed_ssid",
|
||||
"dot11.device.last_probed_ssid",
|
||||
"dot11.advertisedssid.ssid"
|
||||
);
|
||||
const firstSeenAt = timestampValue(firstValue(record, "kismet.device.base.first_time", "first_time", "firstSeen"), now);
|
||||
const lastSeenAt = timestampValue(firstValue(record, "kismet.device.base.last_time", "last_time", "lastSeen"), now);
|
||||
const displayName = stringValue(record, "kismet.device.base.commonname", "kismet.device.base.name", "name") ?? ssid;
|
||||
return {
|
||||
key,
|
||||
technology: classify(record),
|
||||
macAddress,
|
||||
displayName,
|
||||
ssid,
|
||||
manufacturer: stringValue(record, "kismet.device.base.manuf", "manufacturer", "manuf"),
|
||||
channel: stringValue(record, "kismet.device.base.channel", "channel"),
|
||||
encryption: stringValue(record, "kismet.device.base.crypt", "encryption", "crypt", "dot11.advertisedssid.crypt"),
|
||||
firstSeenAt,
|
||||
lastSeenAt,
|
||||
signalDbm: numberValue(record, "kismet.device.base.signal", "signal", "kismet.common.signal.last_signal")
|
||||
};
|
||||
}
|
||||
|
||||
class KismetClient {
|
||||
constructor(private readonly config: WardrivingConfig) {}
|
||||
|
||||
private async get(path: string): Promise<unknown> {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
try {
|
||||
const credentials = JSON.parse(await readFile(this.config.authPath, "utf8")) as { username?: unknown; password?: unknown };
|
||||
if (typeof credentials.username === "string" && typeof credentials.password === "string") {
|
||||
headers.Authorization = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}`;
|
||||
}
|
||||
} catch {
|
||||
// Kismet may be configured without an auth file on development hosts.
|
||||
}
|
||||
const response = await fetch(`${this.config.kismetUrl}${path}`, { headers, signal: AbortSignal.timeout(3_500) });
|
||||
if (!response.ok) throw new Error(`KISMET_HTTP_${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async status(): Promise<KismetStatus> {
|
||||
try {
|
||||
const payload = asRecord(await this.get("/system/status.json"));
|
||||
const version = payload ? stringValue(payload, "kismet.system.version", "version") : null;
|
||||
return { available: true, running: true, version, message: version ? `Kismet ${version} is connected.` : "Kismet is connected." };
|
||||
} catch {
|
||||
return { available: false, running: false, version: null, message: "Kismet is not reachable. Start a session after checking the capture adapters." };
|
||||
}
|
||||
}
|
||||
|
||||
async devices(now: string): Promise<KismetDevice[]> {
|
||||
let payload: unknown;
|
||||
try {
|
||||
const lookbackSeconds = Math.max(5, this.config.pollSeconds * 2);
|
||||
payload = await this.get(`/devices/last-time/-${lookbackSeconds}/devices.json`);
|
||||
} catch {
|
||||
// Older Kismet releases may not expose the device-view endpoint.
|
||||
// Keep the complete-list fallback for those versions, but avoid it on
|
||||
// normal polls because it can be very large on a moving vehicle.
|
||||
try {
|
||||
payload = await this.get("/devices/all_devices.json");
|
||||
} catch {
|
||||
payload = await this.get("/devices/last-time/0/devices.json");
|
||||
}
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
const result: KismetDevice[] = [];
|
||||
for (const record of deviceRecords(payload)) {
|
||||
const device = normalizeKismetDevice(record, now);
|
||||
if (!device || seen.has(device.key)) continue;
|
||||
seen.add(device.key);
|
||||
result.push(device);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export class WardrivingStore {
|
||||
constructor(private readonly database: CompanionDatabase, private readonly config: WardrivingConfig) {}
|
||||
|
||||
activeSession(): SessionRow | null {
|
||||
return this.readSession(this.database.prepare(
|
||||
`SELECT id, started_at AS startedAt, ended_at AS endedAt, state,
|
||||
wifi_interface AS wifiInterface, bluetooth_interface AS bluetoothInterface, error_message AS errorMessage
|
||||
FROM wardriving_sessions WHERE state = 'running' LIMIT 1`
|
||||
).get());
|
||||
}
|
||||
|
||||
startSession(actorUserId: number | null, wifiInterface: string | null, bluetoothInterface: string | null): SessionRow {
|
||||
const now = new Date().toISOString();
|
||||
const result = this.database.prepare(
|
||||
`INSERT INTO wardriving_sessions
|
||||
(started_at, state, wifi_interface, bluetooth_interface, started_by)
|
||||
VALUES (?, 'running', ?, ?, ?)`
|
||||
).run(now, wifiInterface, bluetoothInterface, actorUserId);
|
||||
return this.readSession(this.database.prepare(
|
||||
`SELECT id, started_at AS startedAt, ended_at AS endedAt, state,
|
||||
wifi_interface AS wifiInterface, bluetooth_interface AS bluetoothInterface, error_message AS errorMessage
|
||||
FROM wardriving_sessions WHERE id = ?`
|
||||
).get(Number(result.lastInsertRowid)))!;
|
||||
}
|
||||
|
||||
stopSession(actorUserId: number | null, state: "stopped" | "error" = "stopped", errorMessage: string | null = null): SessionRow | null {
|
||||
const active = this.activeSession();
|
||||
if (!active) return null;
|
||||
this.database.prepare(
|
||||
`UPDATE wardriving_sessions SET state = ?, ended_at = ?, stopped_by = ?, error_message = ? WHERE id = ?`
|
||||
).run(state, new Date().toISOString(), actorUserId, errorMessage, active.id);
|
||||
return this.readSession(this.database.prepare(
|
||||
`SELECT id, started_at AS startedAt, ended_at AS endedAt, state,
|
||||
wifi_interface AS wifiInterface, bluetooth_interface AS bluetoothInterface, error_message AS errorMessage
|
||||
FROM wardriving_sessions WHERE id = ?`
|
||||
).get(active.id));
|
||||
}
|
||||
|
||||
record(sessionId: number, observations: Observation[], gps: GpsFix | null): void {
|
||||
if (observations.length === 0) return;
|
||||
const transaction = this.database.transaction(() => {
|
||||
for (const observation of observations) {
|
||||
this.database.prepare(
|
||||
`INSERT INTO wardriving_devices
|
||||
(kismet_key, technology, mac_address, display_name, ssid, manufacturer, channel, encryption,
|
||||
first_seen_at, last_seen_at, strongest_signal_dbm, latest_latitude, latest_longitude,
|
||||
latest_accuracy_meters, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(kismet_key) DO UPDATE SET
|
||||
technology = excluded.technology,
|
||||
mac_address = COALESCE(excluded.mac_address, wardriving_devices.mac_address),
|
||||
display_name = COALESCE(excluded.display_name, wardriving_devices.display_name),
|
||||
ssid = COALESCE(excluded.ssid, wardriving_devices.ssid),
|
||||
manufacturer = COALESCE(excluded.manufacturer, wardriving_devices.manufacturer),
|
||||
channel = COALESCE(excluded.channel, wardriving_devices.channel),
|
||||
encryption = COALESCE(excluded.encryption, wardriving_devices.encryption),
|
||||
first_seen_at = MIN(wardriving_devices.first_seen_at, excluded.first_seen_at),
|
||||
last_seen_at = MAX(wardriving_devices.last_seen_at, excluded.last_seen_at),
|
||||
strongest_signal_dbm = CASE
|
||||
WHEN excluded.strongest_signal_dbm IS NULL THEN wardriving_devices.strongest_signal_dbm
|
||||
WHEN wardriving_devices.strongest_signal_dbm IS NULL THEN excluded.strongest_signal_dbm
|
||||
ELSE MAX(wardriving_devices.strongest_signal_dbm, excluded.strongest_signal_dbm) END,
|
||||
latest_latitude = COALESCE(excluded.latest_latitude, wardriving_devices.latest_latitude),
|
||||
latest_longitude = COALESCE(excluded.latest_longitude, wardriving_devices.latest_longitude),
|
||||
latest_accuracy_meters = COALESCE(excluded.latest_accuracy_meters, wardriving_devices.latest_accuracy_meters),
|
||||
updated_at = excluded.updated_at`
|
||||
).run(
|
||||
observation.key, observation.technology, observation.macAddress, observation.displayName,
|
||||
observation.ssid, observation.manufacturer, observation.channel, observation.encryption,
|
||||
observation.firstSeenAt, observation.lastSeenAt, observation.signalDbm,
|
||||
gps?.latitude ?? null, gps?.longitude ?? null, gps?.accuracyMeters ?? null, observation.observedAt
|
||||
);
|
||||
const device = this.database.prepare("SELECT id FROM wardriving_devices WHERE kismet_key = ?").get(observation.key) as { id: number };
|
||||
this.database.prepare(
|
||||
`INSERT OR IGNORE INTO wardriving_sightings
|
||||
(session_id, device_id, observed_at, latitude, longitude, accuracy_meters, signal_dbm, channel, source)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
).run(
|
||||
sessionId, device.id, observation.observedAt, gps?.latitude ?? null, gps?.longitude ?? null,
|
||||
gps?.accuracyMeters ?? null, observation.signalDbm, observation.channel, observation.source
|
||||
);
|
||||
}
|
||||
this.database.prepare(
|
||||
`DELETE FROM wardriving_sightings WHERE id IN
|
||||
(SELECT id FROM wardriving_sightings ORDER BY id DESC LIMIT -1 OFFSET ?)`
|
||||
).run(this.config.maxSightings);
|
||||
});
|
||||
transaction();
|
||||
}
|
||||
|
||||
clear(mode: WardrivingClearMode): { mode: WardrivingClearMode; deletedSightings: number; deletedDevices: number; deletedSessions: number } {
|
||||
if (this.activeSession()) throw new Error("WARDRIVING_SESSION_ACTIVE");
|
||||
const result = this.database.transaction(() => {
|
||||
const sightings = this.database.prepare("DELETE FROM wardriving_sightings").run();
|
||||
const sessions = this.database.prepare("DELETE FROM wardriving_sessions").run();
|
||||
let deletedDevices = 0;
|
||||
if (mode === "all") {
|
||||
deletedDevices = this.database.prepare("DELETE FROM wardriving_devices").run().changes;
|
||||
} else {
|
||||
this.database.prepare(
|
||||
`UPDATE wardriving_devices
|
||||
SET latest_latitude = NULL, latest_longitude = NULL, latest_accuracy_meters = NULL`
|
||||
).run();
|
||||
}
|
||||
return { mode, deletedSightings: sightings.changes, deletedDevices, deletedSessions: sessions.changes };
|
||||
})();
|
||||
return result;
|
||||
}
|
||||
|
||||
latestGps(): GpsFix | null {
|
||||
const row = this.database.prepare(
|
||||
`SELECT received_at AS receivedAt, captured_at AS capturedAt, latitude, longitude, accuracy_meters AS accuracyMeters
|
||||
FROM mobile_phone_state
|
||||
JOIN mobile_devices ON mobile_devices.id = mobile_phone_state.device_id
|
||||
WHERE mobile_devices.revoked_at IS NULL
|
||||
ORDER BY received_at DESC LIMIT 1`
|
||||
).get() as Omit<GpsFix, "ageSeconds"> | undefined;
|
||||
if (!row) return null;
|
||||
const receivedAgeSeconds = (Date.now() - Date.parse(row.receivedAt)) / 1_000;
|
||||
const capturedAgeSeconds = (Date.now() - Date.parse(row.capturedAt)) / 1_000;
|
||||
const ageSeconds = Math.max(0, receivedAgeSeconds, capturedAgeSeconds);
|
||||
if (
|
||||
!Number.isFinite(ageSeconds)
|
||||
|| receivedAgeSeconds < -10
|
||||
|| capturedAgeSeconds < -10
|
||||
|| ageSeconds > 45
|
||||
|| row.accuracyMeters > 250
|
||||
) return null;
|
||||
return { ...row, ageSeconds };
|
||||
}
|
||||
|
||||
statistics() {
|
||||
const row = this.database.prepare(
|
||||
`SELECT COUNT(*) AS devices,
|
||||
SUM(CASE WHEN technology = 'wifi' THEN 1 ELSE 0 END) AS wifiDevices,
|
||||
SUM(CASE WHEN technology = 'bluetooth' THEN 1 ELSE 0 END) AS bluetoothDevices,
|
||||
MAX(last_seen_at) AS lastSeenAt FROM wardriving_devices`
|
||||
).get() as { devices: number; wifiDevices: number | null; bluetoothDevices: number | null; lastSeenAt: string | null };
|
||||
const sightings = this.database.prepare(
|
||||
"SELECT COUNT(*) AS count, SUM(CASE WHEN latitude IS NOT NULL AND longitude IS NOT NULL THEN 1 ELSE 0 END) AS mapped FROM wardriving_sightings"
|
||||
).get() as { count: number; mapped: number | null };
|
||||
const sessions = this.database.prepare("SELECT COUNT(*) AS count FROM wardriving_sessions").get() as { count: number };
|
||||
return {
|
||||
devices: row.devices ?? 0,
|
||||
wifiDevices: row.wifiDevices ?? 0,
|
||||
bluetoothDevices: row.bluetoothDevices ?? 0,
|
||||
sightings: sightings.count ?? 0,
|
||||
mappedSightings: sightings.mapped ?? 0,
|
||||
sessions: sessions.count ?? 0,
|
||||
lastSeenAt: row.lastSeenAt ?? null
|
||||
};
|
||||
}
|
||||
|
||||
devices(limit = 250) {
|
||||
return this.database.prepare(
|
||||
`SELECT id, kismet_key AS key, technology, mac_address AS macAddress, display_name AS displayName,
|
||||
ssid, manufacturer, channel, encryption, first_seen_at AS firstSeenAt, last_seen_at AS lastSeenAt,
|
||||
strongest_signal_dbm AS strongestSignalDbm, latest_latitude AS latestLatitude,
|
||||
latest_longitude AS latestLongitude, latest_accuracy_meters AS latestAccuracyMeters
|
||||
FROM wardriving_devices ORDER BY last_seen_at DESC LIMIT ?`
|
||||
).all(Math.min(Math.max(limit, 1), 500)) as WardrivingSnapshot["devices"];
|
||||
}
|
||||
|
||||
sightings(limit = 1_000, sessionId?: number) {
|
||||
const bounded = Math.min(Math.max(limit, 1), 2_000);
|
||||
const rows = sessionId
|
||||
? this.database.prepare(
|
||||
`SELECT s.id, s.session_id AS sessionId, s.device_id AS deviceId, s.observed_at AS observedAt,
|
||||
s.latitude, s.longitude, s.accuracy_meters AS accuracyMeters, s.signal_dbm AS signalDbm,
|
||||
s.channel, s.source, d.technology, d.display_name AS displayName, d.mac_address AS macAddress
|
||||
FROM wardriving_sightings s JOIN wardriving_devices d ON d.id = s.device_id
|
||||
WHERE s.session_id = ? ORDER BY s.observed_at DESC LIMIT ?`
|
||||
).all(sessionId, bounded)
|
||||
: this.database.prepare(
|
||||
`SELECT s.id, s.session_id AS sessionId, s.device_id AS deviceId, s.observed_at AS observedAt,
|
||||
s.latitude, s.longitude, s.accuracy_meters AS accuracyMeters, s.signal_dbm AS signalDbm,
|
||||
s.channel, s.source, d.technology, d.display_name AS displayName, d.mac_address AS macAddress
|
||||
FROM wardriving_sightings s JOIN wardriving_devices d ON d.id = s.device_id
|
||||
ORDER BY s.observed_at DESC LIMIT ?`
|
||||
).all(bounded);
|
||||
return rows as WardrivingSnapshot["sightings"];
|
||||
}
|
||||
|
||||
sessions(limit = 30) {
|
||||
return this.database.prepare(
|
||||
`SELECT s.id, s.started_at AS startedAt, s.ended_at AS endedAt, s.state,
|
||||
s.wifi_interface AS wifiInterface, s.bluetooth_interface AS bluetoothInterface, s.error_message AS errorMessage,
|
||||
COUNT(DISTINCT x.device_id) AS devices, COUNT(x.id) AS sightings
|
||||
FROM wardriving_sessions s LEFT JOIN wardriving_sightings x ON x.session_id = s.id
|
||||
GROUP BY s.id ORDER BY s.started_at DESC LIMIT ?`
|
||||
).all(Math.min(Math.max(limit, 1), 100)) as Array<SessionRow & { devices: number; sightings: number }>;
|
||||
}
|
||||
|
||||
snapshot(kismet: KismetStatus): WardrivingSnapshot {
|
||||
const active = this.activeSession();
|
||||
const gps = this.latestGps();
|
||||
const session = active
|
||||
? { ...active, devices: this.sessionDeviceCount(active.id), sightings: this.sessionSightings(active.id) }
|
||||
: null;
|
||||
return {
|
||||
supported: this.config.enabled,
|
||||
enabled: this.config.enabled,
|
||||
updatedAt: new Date().toISOString(),
|
||||
running: Boolean(active),
|
||||
kismet,
|
||||
session,
|
||||
gps: {
|
||||
available: gps !== null,
|
||||
fix: gps,
|
||||
message: gps ? `Phone GPS is fresh (${Math.round(gps.accuracyMeters)} m accuracy).` : "Waiting for a fresh phone GPS fix. Unmapped observations are retained."
|
||||
},
|
||||
sources: {
|
||||
wifiInterface: this.config.wifiInterface,
|
||||
bluetoothInterface: this.config.bluetoothInterface,
|
||||
wifiPassive: true,
|
||||
bluetoothMode: "discoverable-metadata",
|
||||
noPairing: true
|
||||
},
|
||||
statistics: this.statistics(),
|
||||
devices: this.devices(),
|
||||
sightings: this.sightings(),
|
||||
recentSessions: this.sessions()
|
||||
};
|
||||
}
|
||||
|
||||
private sessionDeviceCount(id: number): number {
|
||||
return (this.database.prepare("SELECT COUNT(DISTINCT device_id) AS count FROM wardriving_sightings WHERE session_id = ?").get(id) as { count: number }).count;
|
||||
}
|
||||
|
||||
private sessionSightings(id: number): number {
|
||||
return (this.database.prepare("SELECT COUNT(*) AS count FROM wardriving_sightings WHERE session_id = ?").get(id) as { count: number }).count;
|
||||
}
|
||||
|
||||
private readSession(value: unknown): SessionRow | null {
|
||||
return value ? value as SessionRow : null;
|
||||
}
|
||||
}
|
||||
|
||||
export class WardrivingRecorder {
|
||||
private readonly config: WardrivingConfig;
|
||||
private readonly client: KismetClient;
|
||||
private readonly store: WardrivingStore;
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private pollInProgress = false;
|
||||
private lastKismet: KismetStatus = { available: false, running: false, version: null, message: "Kismet has not been checked yet." };
|
||||
|
||||
constructor(database: CompanionDatabase, appConfig: AppConfig) {
|
||||
this.config = getWardrivingConfig(appConfig);
|
||||
this.client = new KismetClient(this.config);
|
||||
this.store = new WardrivingStore(database, this.config);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (!this.config.enabled || this.timer) return;
|
||||
void this.poll();
|
||||
this.timer = setInterval(() => void this.poll(), this.config.pollSeconds * 1_000);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
async snapshot(): Promise<WardrivingSnapshot> {
|
||||
await this.poll();
|
||||
const snapshot = this.store.snapshot(this.lastKismet);
|
||||
await this.writeStatus(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
async snapshotForMobile(): Promise<WardrivingSnapshot> {
|
||||
const snapshot = await this.snapshot();
|
||||
return {
|
||||
...snapshot,
|
||||
devices: snapshot.devices.slice(0, 20),
|
||||
sightings: snapshot.sightings.slice(0, 100),
|
||||
recentSessions: snapshot.recentSessions.slice(0, 10)
|
||||
};
|
||||
}
|
||||
|
||||
async action(action: WardrivingAction, actorUserId: number | null): Promise<WardrivingSnapshot> {
|
||||
if (!this.config.enabled) throw new Error("WARDRIVING_DISABLED");
|
||||
if (action === "start" || action === "restart") {
|
||||
await requestWardrivingAction(this.config, action === "restart" ? "restart" : "start");
|
||||
if (action === "restart") this.store.stopSession(actorUserId, "stopped", "Session restarted by administrator");
|
||||
if (!this.store.activeSession()) this.store.startSession(actorUserId, this.config.wifiInterface, this.config.bluetoothInterface);
|
||||
} else {
|
||||
await requestWardrivingAction(this.config, "stop");
|
||||
this.store.stopSession(actorUserId);
|
||||
}
|
||||
await this.poll();
|
||||
const snapshot = this.store.snapshot(this.lastKismet);
|
||||
await this.writeStatus(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
clear(mode: WardrivingClearMode) {
|
||||
return this.store.clear(mode);
|
||||
}
|
||||
|
||||
storeInstance(): WardrivingStore { return this.store; }
|
||||
|
||||
private async poll(): Promise<void> {
|
||||
if (this.pollInProgress || !this.config.enabled) return;
|
||||
this.pollInProgress = true;
|
||||
try {
|
||||
this.lastKismet = await this.client.status();
|
||||
const session = this.store.activeSession();
|
||||
if (session && this.lastKismet.available) {
|
||||
try {
|
||||
const now = new Date().toISOString();
|
||||
const devices = await this.client.devices(now);
|
||||
const observations = devices.map((device) => ({ ...device, observedAt: now, source: device.technology }));
|
||||
this.store.record(session.id, observations, this.store.latestGps());
|
||||
} catch (error) {
|
||||
this.lastKismet = { ...this.lastKismet, message: error instanceof Error ? error.message : "Kismet device data could not be read" };
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.pollInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async writeStatus(snapshot: WardrivingSnapshot): Promise<void> {
|
||||
try {
|
||||
await mkdir(dirname(this.config.statusPath), { recursive: true, mode: 0o750 });
|
||||
const temporary = `${this.config.statusPath}.tmp`;
|
||||
await writeFile(temporary, `${JSON.stringify(snapshot)}\n`, { mode: 0o644 });
|
||||
await rename(temporary, this.config.statusPath);
|
||||
} catch {
|
||||
// The API remains authoritative; status persistence is best effort on development hosts.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function readWardrivingStatus(config: AppConfig): Promise<WardrivingSnapshot | null> {
|
||||
const wardriving = getWardrivingConfig(config);
|
||||
try {
|
||||
return JSON.parse(await readFile(wardriving.statusPath, "utf8")) as WardrivingSnapshot;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestWardrivingAction(_config: WardrivingConfig, action: WardrivingAction): Promise<void> {
|
||||
await execFileAsync(
|
||||
"/usr/bin/sudo",
|
||||
["-n", "/usr/local/sbin/pi-car-companion-wardriving-control", action],
|
||||
{ timeout: 15_000, maxBuffer: 16 * 1024 }
|
||||
);
|
||||
}
|
||||
@@ -169,6 +169,22 @@ describe("authentication boundary", () => {
|
||||
headUnit: { available: false, state: "disabled" }
|
||||
});
|
||||
|
||||
expect((await app.inject({ method: "GET", url: "/api/wardriving" })).statusCode).toBe(401);
|
||||
const wardriving = await app.inject({ method: "GET", url: "/api/wardriving", headers: { cookie: `${SESSION_COOKIE}=${sessionCookie?.value ?? ""}` } });
|
||||
expect(wardriving.statusCode).toBe(200);
|
||||
expect(wardriving.json()).toMatchObject({ supported: false, enabled: false, running: false });
|
||||
const disabledWardrivingAction = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/wardriving/actions",
|
||||
headers: {
|
||||
...mutationHeaders(token),
|
||||
cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
|
||||
},
|
||||
payload: { action: "start" }
|
||||
});
|
||||
expect(disabledWardrivingAction.statusCode).toBe(503);
|
||||
expect(disabledWardrivingAction.json()).toMatchObject({ error: { code: "WARDRIVING_DISABLED" } });
|
||||
|
||||
const update = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/system/update",
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { openDatabase } from "../src/database.js";
|
||||
import { normalizeKismetDevice, WardrivingStore } from "../src/wardriving.js";
|
||||
|
||||
describe("Kismet device normalization", () => {
|
||||
it("reads the nested fields returned by the live device API", () => {
|
||||
const device = normalizeKismetDevice({
|
||||
"kismet.device.base.key": "IEEE802.11-00:11:22:33:44:55",
|
||||
"kismet.device.base.macaddr": "00:11:22:33:44:55",
|
||||
"kismet.device.base.phyname": "IEEE802.11",
|
||||
"kismet.device.base.type": "Wi-Fi AP",
|
||||
"kismet.device.base.name": "",
|
||||
"kismet.device.base.commonname": "Cafe WiFi",
|
||||
"kismet.device.base.first_time": 1787565600,
|
||||
"kismet.device.base.last_time": 1787565660,
|
||||
"kismet.device.base.signal": { "kismet.common.signal.last_signal": -39 },
|
||||
"kismet.device.base.channel": "6",
|
||||
"kismet.device.base.crypt": "WPA2",
|
||||
"dot11.device": {
|
||||
"dot11.device.last_beaconed_ssid_record": {
|
||||
"dot11.advertisedssid.ssid": "Cafe WiFi"
|
||||
}
|
||||
}
|
||||
}, "2026-08-24T10:00:00.000Z");
|
||||
|
||||
expect(device).toMatchObject({
|
||||
technology: "wifi",
|
||||
macAddress: "00:11:22:33:44:55",
|
||||
displayName: "Cafe WiFi",
|
||||
ssid: "Cafe WiFi",
|
||||
channel: "6",
|
||||
encryption: "WPA2",
|
||||
signalDbm: -39,
|
||||
firstSeenAt: "2026-08-24T10:00:00.000Z",
|
||||
lastSeenAt: "2026-08-24T10:01:00.000Z"
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies Bluetooth metadata and nested signal values", () => {
|
||||
const device = normalizeKismetDevice({
|
||||
"kismet.device.base.key": "BTLE-AA:BB:CC:DD:EE:FF",
|
||||
"kismet.device.base.macaddr": "aa:bb:cc:dd:ee:ff",
|
||||
"kismet.device.base.phyname": "BTLE",
|
||||
"kismet.device.base.type": "Bluetooth LE",
|
||||
"kismet.device.base.name": "Beacon tag",
|
||||
"kismet.device.base.signal": { "kismet.common.signal.last_signal": -71 },
|
||||
"kismet.device.base.last_time": "1787565660"
|
||||
}, "2026-08-24T10:00:00.000Z");
|
||||
|
||||
expect(device).toMatchObject({
|
||||
technology: "bluetooth",
|
||||
macAddress: "AA:BB:CC:DD:EE:FF",
|
||||
displayName: "Beacon tag",
|
||||
signalDbm: -71,
|
||||
lastSeenAt: "2026-08-24T10:01:00.000Z"
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("wardriving storage", () => {
|
||||
it("keeps device metadata, mapped GPS sightings, and bounded session summaries", () => {
|
||||
const database = openDatabase(":memory:");
|
||||
const store = new WardrivingStore(database, {
|
||||
enabled: true,
|
||||
statusPath: "/tmp/wardriving-status.json",
|
||||
kismetUrl: "http://127.0.0.1:2501",
|
||||
authPath: "/tmp/wardriving-credentials.json",
|
||||
pollSeconds: 5,
|
||||
maxSightings: 10,
|
||||
wifiInterface: "wlan2",
|
||||
bluetoothInterface: "hci0"
|
||||
});
|
||||
const session = store.startSession(null, "wlan2", "hci0");
|
||||
store.record(session.id, [{
|
||||
key: "aa:bb:cc:dd:ee:ff",
|
||||
technology: "wifi",
|
||||
macAddress: "AA:BB:CC:DD:EE:FF",
|
||||
displayName: "Cafe WiFi",
|
||||
ssid: "Cafe WiFi",
|
||||
manufacturer: "Example",
|
||||
channel: "6",
|
||||
encryption: "WPA2",
|
||||
firstSeenAt: "2026-08-24T10:00:00.000Z",
|
||||
lastSeenAt: "2026-08-24T10:00:00.000Z",
|
||||
signalDbm: -42,
|
||||
observedAt: "2026-08-24T10:00:00.000Z",
|
||||
source: "wifi"
|
||||
}], {
|
||||
receivedAt: "2026-08-24T10:00:01.000Z",
|
||||
capturedAt: "2026-08-24T10:00:00.000Z",
|
||||
latitude: 55.6761,
|
||||
longitude: 12.5683,
|
||||
accuracyMeters: 5,
|
||||
ageSeconds: 0
|
||||
});
|
||||
|
||||
expect(store.statistics()).toMatchObject({ devices: 1, wifiDevices: 1, sightings: 1, mappedSightings: 1 });
|
||||
expect(store.devices()).toMatchObject([{ ssid: "Cafe WiFi", latestLatitude: 55.6761 }]);
|
||||
expect(store.sightings()).toMatchObject([{ latitude: 55.6761, technology: "wifi" }]);
|
||||
expect(store.sessions()).toMatchObject([{ state: "running", devices: 1, sightings: 1 }]);
|
||||
store.stopSession(null);
|
||||
expect(store.clear("history")).toMatchObject({ deletedSightings: 1, deletedDevices: 0, deletedSessions: 1 });
|
||||
expect(store.devices()).toMatchObject([{ latestLatitude: null, latestLongitude: null, latestAccuracyMeters: null }]);
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("refuses to clear data while a capture session is active", () => {
|
||||
const database = openDatabase(":memory:");
|
||||
const store = new WardrivingStore(database, {
|
||||
enabled: true,
|
||||
statusPath: "/tmp/wardriving-status.json",
|
||||
kismetUrl: "http://127.0.0.1:2501",
|
||||
authPath: "/tmp/wardriving-credentials.json",
|
||||
pollSeconds: 5,
|
||||
maxSightings: 10,
|
||||
wifiInterface: null,
|
||||
bluetoothInterface: "hci0"
|
||||
});
|
||||
store.startSession(null, null, "hci0");
|
||||
expect(() => store.clear("all")).toThrow("WARDRIVING_SESSION_ACTIVE");
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("uses only a fresh location from an active paired phone", () => {
|
||||
const database = openDatabase(":memory:");
|
||||
const store = new WardrivingStore(database, {
|
||||
enabled: true,
|
||||
statusPath: "/tmp/wardriving-status.json",
|
||||
kismetUrl: "http://127.0.0.1:2501",
|
||||
authPath: "/tmp/wardriving-credentials.json",
|
||||
pollSeconds: 5,
|
||||
maxSightings: 10,
|
||||
wifiInterface: null,
|
||||
bluetoothInterface: "hci0"
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
database.prepare(
|
||||
`INSERT INTO mobile_devices (id, name, token_hash, created_at, last_seen_at, revoked_at)
|
||||
VALUES ('phone-a', 'Phone A', 'token-a', ?, ?, NULL)`
|
||||
).run(now, now);
|
||||
database.prepare(
|
||||
`INSERT INTO mobile_phone_state
|
||||
(device_id, received_at, captured_at, latitude, longitude, accuracy_meters)
|
||||
VALUES ('phone-a', ?, ?, 55.6761, 12.5683, 5)`
|
||||
).run(now, now);
|
||||
expect(store.latestGps()).toMatchObject({ latitude: 55.6761, longitude: 12.5683 });
|
||||
|
||||
database.prepare("UPDATE mobile_devices SET revoked_at = ? WHERE id = 'phone-a'").run(now);
|
||||
expect(store.latestGps()).toBeNull();
|
||||
database.close();
|
||||
});
|
||||
|
||||
it("rejects a phone fix whose captured timestamp is stale even when delivery is recent", () => {
|
||||
const database = openDatabase(":memory:");
|
||||
const store = new WardrivingStore(database, {
|
||||
enabled: true,
|
||||
statusPath: "/tmp/wardriving-status.json",
|
||||
kismetUrl: "http://127.0.0.1:2501",
|
||||
authPath: "/tmp/wardriving-credentials.json",
|
||||
pollSeconds: 5,
|
||||
maxSightings: 10,
|
||||
wifiInterface: null,
|
||||
bluetoothInterface: "hci0"
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
database.prepare(
|
||||
`INSERT INTO mobile_devices (id, name, token_hash, created_at, last_seen_at, revoked_at)
|
||||
VALUES ('phone-b', 'Phone B', 'token-b', ?, ?, NULL)`
|
||||
).run(now, now);
|
||||
database.prepare(
|
||||
`INSERT INTO mobile_phone_state
|
||||
(device_id, received_at, captured_at, latitude, longitude, accuracy_meters)
|
||||
VALUES ('phone-b', ?, ?, 55.6761, 12.5683, 5)`
|
||||
).run(now, "2026-01-01T00:00:00.000Z");
|
||||
expect(store.latestGps()).toBeNull();
|
||||
database.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
[Unit]
|
||||
Description=Pi Car Companion Kismet radio discovery session
|
||||
After=network.target bluetooth.service
|
||||
Wants=bluetooth.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
SupplementaryGroups=netdev
|
||||
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW
|
||||
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW
|
||||
ExecStart=/usr/bin/kismet --no-ncurses-wrapper --no-line-wrap
|
||||
Restart=on-failure
|
||||
RestartSec=8s
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
RestrictRealtime=true
|
||||
LockPersonality=true
|
||||
ReadWritePaths=/var/lib/pi-car-companion/kismet
|
||||
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK AF_PACKET AF_BLUETOOTH
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -6,3 +6,6 @@ pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-power powerof
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-bluetooth-control on
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-bluetooth-control off
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-bluetooth-control discoverable
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-wardriving-control start
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-wardriving-control stop
|
||||
pi-companion ALL=(root) NOPASSWD: /usr/local/sbin/pi-car-companion-wardriving-control restart
|
||||
+8
-5
@@ -3,6 +3,7 @@ import {
|
||||
ArrowClockwise,
|
||||
AndroidLogo,
|
||||
Bluetooth,
|
||||
Broadcast,
|
||||
CarProfile,
|
||||
CheckCircle,
|
||||
Cpu,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
} from "@phosphor-icons/react";
|
||||
import { AdbPage } from "./AdbPage";
|
||||
import { CarPage } from "./CarPage";
|
||||
import { WardrivingPage } from "./WardrivingPage";
|
||||
import {
|
||||
ApiError,
|
||||
getAuthState,
|
||||
@@ -53,9 +55,9 @@ const TripsPage = lazy(async () => {
|
||||
});
|
||||
|
||||
type Screen = "loading" | "setup" | "login" | "dashboard" | "fatal";
|
||||
type DashboardPage = "home" | "car" | "trips" | "adb" | "network" | "settings";
|
||||
type DashboardPage = "home" | "car" | "trips" | "adb" | "network" | "wardriving" | "settings";
|
||||
|
||||
const dashboardPages = new Set<DashboardPage>(["home", "car", "trips", "adb", "network", "settings"]);
|
||||
const dashboardPages = new Set<DashboardPage>(["home", "car", "trips", "adb", "network", "wardriving", "settings"]);
|
||||
|
||||
function pageFromLocation(): DashboardPage {
|
||||
const page = window.location.hash.replace(/^#\/?/, "");
|
||||
@@ -242,6 +244,7 @@ function Dashboard({ auth, onLoggedOut }: { auth: AuthState; onLoggedOut: () =>
|
||||
<button className={`nav-item ${page === "trips" ? "active" : ""}`} onClick={() => navigate("trips")}><Path size={24} weight={page === "trips" ? "fill" : "regular"} /><span>Trips</span></button>
|
||||
<button className={`nav-item ${page === "adb" ? "active" : ""}`} onClick={() => navigate("adb")}><AndroidLogo size={24} weight={page === "adb" ? "fill" : "regular"} /><span>ADB</span></button>
|
||||
<button className={`nav-item ${page === "network" ? "active" : ""}`} onClick={() => navigate("network")}><WifiHigh size={24} weight={page === "network" ? "fill" : "regular"} /><span>Network</span></button>
|
||||
<button className={`nav-item ${page === "wardriving" ? "active" : ""}`} onClick={() => navigate("wardriving")}><Broadcast size={24} weight={page === "wardriving" ? "fill" : "regular"} /><span>Wardriving</span></button>
|
||||
<button className={`nav-item ${page === "settings" ? "active" : ""}`} onClick={() => navigate("settings")}><Gear size={24} weight={page === "settings" ? "fill" : "regular"} /><span>Settings</span></button>
|
||||
</nav>
|
||||
<button className="nav-item logout" onClick={() => void logout()}><SignOut size={24} /><span>Sign out</span></button>
|
||||
@@ -249,8 +252,8 @@ function Dashboard({ auth, onLoggedOut }: { auth: AuthState; onLoggedOut: () =>
|
||||
<main className="dashboard">
|
||||
<header className="dashboard-header">
|
||||
<div>
|
||||
<p className="eyebrow">{page === "home" ? "System overview" : page === "car" ? "Live vehicle signals" : page === "trips" ? "Drive history" : page === "adb" ? "Android device bridge" : page === "network" ? "Live diagnostics" : "Companion settings"}</p>
|
||||
<h1>{page === "home" ? status?.hostname ?? "Your Raspberry Pi" : page === "car" ? "Car" : page === "trips" ? "Trips" : page === "adb" ? "ADB" : page === "network" ? "Network activity" : "Settings"}</h1>
|
||||
<p className="eyebrow">{page === "home" ? "System overview" : page === "car" ? "Live vehicle signals" : page === "trips" ? "Drive history" : page === "adb" ? "Android device bridge" : page === "network" ? "Live diagnostics" : page === "wardriving" ? "Live radio mapping" : "Companion settings"}</p>
|
||||
<h1>{page === "home" ? status?.hostname ?? "Your Raspberry Pi" : page === "car" ? "Car" : page === "trips" ? "Trips" : page === "adb" ? "ADB" : page === "network" ? "Network activity" : page === "wardriving" ? "Wardriving" : "Settings"}</h1>
|
||||
</div>
|
||||
<div className="header-actions">
|
||||
<div className={`connection-state ${connection}`}>
|
||||
@@ -265,7 +268,7 @@ function Dashboard({ auth, onLoggedOut }: { auth: AuthState; onLoggedOut: () =>
|
||||
{page === "home" ? <>
|
||||
{error && <div className="status-error" role="alert"><WarningCircle size={22} />{error}<button onClick={() => void refresh()}>Try again</button></div>}
|
||||
{!status ? <DashboardSkeleton /> : <StatusContent status={status} />}
|
||||
</> : page === "car" ? <CarPage csrfToken={auth.csrfToken} /> : page === "trips" ? <Suspense fallback={<div className="trips-skeleton"><div /><div /><div /></div>}><TripsPage /></Suspense> : page === "adb" ? <AdbPage csrfToken={auth.csrfToken} /> : page === "network" ? <NetworkActivityPage /> : <SettingsPage csrfToken={auth.csrfToken} />}
|
||||
</> : page === "car" ? <CarPage csrfToken={auth.csrfToken} /> : page === "trips" ? <Suspense fallback={<div className="trips-skeleton"><div /><div /><div /></div>}><TripsPage /></Suspense> : page === "adb" ? <AdbPage csrfToken={auth.csrfToken} /> : page === "network" ? <NetworkActivityPage /> : page === "wardriving" ? <WardrivingPage csrfToken={auth.csrfToken} /> : <SettingsPage csrfToken={auth.csrfToken} />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import L from "leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import {
|
||||
ArrowClockwise,
|
||||
Bluetooth,
|
||||
Broadcast,
|
||||
CheckCircle,
|
||||
CircleNotch,
|
||||
MapPin,
|
||||
PlayCircle,
|
||||
ShieldCheck,
|
||||
StopCircle,
|
||||
Trash,
|
||||
WarningCircle,
|
||||
WifiHigh
|
||||
} from "@phosphor-icons/react";
|
||||
import { ApiError, clearWardriving, getWardriving, wardrivingAction, type WardrivingDevice, type WardrivingSnapshot, type WardrivingTechnology } from "./api";
|
||||
|
||||
type Filter = "all" | WardrivingTechnology;
|
||||
|
||||
export function WardrivingPage({ csrfToken }: { csrfToken: string }) {
|
||||
const [snapshot, setSnapshot] = useState<WardrivingSnapshot | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [notice, setNotice] = useState("");
|
||||
const [filter, setFilter] = useState<Filter>("all");
|
||||
const [busy, setBusy] = useState<"start" | "stop" | "restart" | "clear" | null>(null);
|
||||
const [clearMode, setClearMode] = useState<"history" | "all" | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setSnapshot(await getWardriving());
|
||||
setError("");
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Wardriving status could not be loaded");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const interval = window.setInterval(() => void refresh(), 3_000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [refresh]);
|
||||
|
||||
async function changeSession(action: "start" | "stop" | "restart") {
|
||||
setBusy(action);
|
||||
setError("");
|
||||
setNotice("");
|
||||
try {
|
||||
setSnapshot(await wardrivingAction(action, csrfToken));
|
||||
setNotice(action === "stop" ? "Wardriving session stopped." : action === "restart" ? "Wardriving session restarted." : "Wardriving session started.");
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "The wardriving session could not be changed");
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function clearData() {
|
||||
if (!clearMode) return;
|
||||
setBusy("clear");
|
||||
setError("");
|
||||
try {
|
||||
await clearWardriving(clearMode, csrfToken);
|
||||
setClearMode(null);
|
||||
setNotice(clearMode === "all" ? "All wardriving data was cleared." : "Sightings and session history were cleared.");
|
||||
await refresh();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Wardriving data could not be cleared");
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
const devices = snapshot?.devices.filter((device) => filter === "all" || device.technology === filter) ?? [];
|
||||
const mapped = snapshot?.sightings.filter((sighting) => sighting.latitude !== null && sighting.longitude !== null) ?? [];
|
||||
|
||||
return (
|
||||
<div className="wardriving-page">
|
||||
{error && <div className="status-error" role="alert"><WarningCircle size={22} />{error}<button onClick={() => void refresh()}>Try again</button></div>}
|
||||
{notice && <div className="status-success" role="status"><CheckCircle size={21} />{notice}</div>}
|
||||
|
||||
<section className="wardriving-hero">
|
||||
<div className="wardriving-hero-copy">
|
||||
<div className="wardriving-kicker"><Broadcast size={17} weight="fill" /> Low-impact radio log</div>
|
||||
<h2>See the radio landscape around the car.</h2>
|
||||
<p>Kismet watches the configured WiFi and Bluetooth radios. The paired phone supplies the moving GPS fix so each observation can be placed on the map.</p>
|
||||
</div>
|
||||
<div className={`wardriving-session-state ${snapshot?.running ? "is-running" : ""}`}>
|
||||
<span className="wardriving-pulse" aria-hidden="true" />
|
||||
<div><strong>{snapshot?.running ? "Session live" : "Session idle"}</strong><small>{snapshot?.session ? `Started ${new Date(snapshot.session.startedAt).toLocaleTimeString()}` : "Start a session when you are ready to drive"}</small></div>
|
||||
</div>
|
||||
<div className="wardriving-actions">
|
||||
{snapshot?.running ? <>
|
||||
<button className="danger-button" onClick={() => void changeSession("stop")} disabled={busy !== null}><StopCircle size={22} />{busy === "stop" ? "Stopping…" : "Stop session"}</button>
|
||||
<button className="secondary-button" onClick={() => void changeSession("restart")} disabled={busy !== null}><ArrowClockwise size={21} />Restart</button>
|
||||
</> : <button className="primary-button" onClick={() => void changeSession("start")} disabled={busy !== null || !snapshot?.enabled}><PlayCircle size={22} />{busy === "start" ? "Starting…" : "Start session"}</button>}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{!snapshot?.enabled && <section className="wardriving-empty"><WarningCircle size={42} /><h2>Wardriving is not enabled</h2><p>Run the latest installer and set a dedicated monitor-mode WiFi adapter in <code>companion.env</code>. The built-in hotspot radio should stay dedicated to the car network.</p></section>}
|
||||
|
||||
<section className="wardriving-stat-grid" aria-label="Wardriving statistics">
|
||||
<WardrivingStat icon={<WifiHigh size={23} />} label="WiFi networks" value={snapshot?.statistics.wifiDevices ?? 0} detail="Unique devices" />
|
||||
<WardrivingStat icon={<Bluetooth size={23} />} label="Bluetooth devices" value={snapshot?.statistics.bluetoothDevices ?? 0} detail="Classic + BLE" />
|
||||
<WardrivingStat icon={<MapPin size={23} />} label="Mapped sightings" value={snapshot?.statistics.mappedSightings ?? 0} detail={`${snapshot?.statistics.sightings ?? 0} total observations`} />
|
||||
<WardrivingStat icon={<ShieldCheck size={23} />} label="Phone GPS" value={snapshot?.gps.available ? `${Math.round(snapshot.gps.fix?.accuracyMeters ?? 0)} m` : "Waiting"} detail={snapshot?.gps.message ?? "Pair a phone to map sightings"} textValue />
|
||||
</section>
|
||||
|
||||
<div className="wardriving-workspace">
|
||||
<section className="wardriving-map-panel">
|
||||
<div className="wardriving-panel-heading"><div><h2>Observation map</h2><p>{mapped.length.toLocaleString()} recent points with a fresh phone fix.</p></div><span className="wardriving-map-legend"><i className="wifi" /> WiFi <i className="bluetooth" /> Bluetooth</span></div>
|
||||
<WardrivingMap sightings={mapped} />
|
||||
</section>
|
||||
|
||||
<section className="wardriving-devices-panel">
|
||||
<div className="wardriving-panel-heading"><div><h2>Devices in range</h2><p>Broadcast metadata only; no payloads or credentials are stored.</p></div></div>
|
||||
<div className="wardriving-filters" role="tablist" aria-label="Device type filter">
|
||||
{(["all", "wifi", "bluetooth"] as Filter[]).map((item) => <button key={item} role="tab" aria-selected={filter === item} className={filter === item ? "active" : ""} onClick={() => setFilter(item)}>{item === "all" ? "All" : item === "wifi" ? "WiFi" : "Bluetooth"}</button>)}
|
||||
</div>
|
||||
<div className="wardriving-device-list">
|
||||
{devices.length ? devices.map((device) => <WardrivingDeviceRow key={device.id} device={device} />) : <div className="wardriving-list-empty"><CircleNotch size={28} /><span>{snapshot?.running ? "Waiting for devices from Kismet…" : "Start a session to populate this list."}</span></div>}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="wardriving-bottom-grid">
|
||||
<div className="wardriving-source-panel">
|
||||
<div className="wardriving-panel-heading"><div><h2>Capture sources</h2><p>Keep the hotspot radio separate from monitor capture.</p></div></div>
|
||||
<dl className="wardriving-source-list"><div><dt>WiFi adapter</dt><dd><WifiHigh size={18} />{snapshot?.sources.wifiInterface ?? "Auto-select"}</dd></div><div><dt>Bluetooth adapter</dt><dd><Bluetooth size={18} />{snapshot?.sources.bluetoothInterface ?? "Not configured"}</dd></div><div><dt>Capture mode</dt><dd><ShieldCheck size={18} />WiFi passive · BT discoverable</dd></div></dl>
|
||||
<p className="wardriving-note">Kismet uses passive WiFi capture and a discoverable-device Bluetooth scan. It does not pair, enumerate services, or access payloads. Use a dedicated USB WiFi adapter capable of monitor mode; do not use the adapter carrying the Pi hotspot or upstream connection.</p>
|
||||
</div>
|
||||
<div className="wardriving-source-panel">
|
||||
<div className="wardriving-panel-heading"><div><h2>Data controls</h2><p>{snapshot?.statistics.sessions ?? 0} sessions · bounded to 250,000 sightings.</p></div><Trash size={24} /></div>
|
||||
<p className="wardriving-note">Clear stored map points when you are done with a drive. Devices are retained until you clear all data so repeated visits remain comparable.</p>
|
||||
<div className="wardriving-clear-actions"><button className="secondary-button" onClick={() => setClearMode("history")} disabled={snapshot?.running || busy !== null}>Clear history</button><button className="danger-button" onClick={() => setClearMode("all")} disabled={snapshot?.running || busy !== null}>Clear all data</button></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{clearMode && <div className="modal-backdrop" role="presentation" onMouseDown={() => busy === null && setClearMode(null)}><div className="confirm-dialog" role="dialog" aria-modal="true" aria-labelledby="wardriving-clear-title" onMouseDown={(event) => event.stopPropagation()}><h2 id="wardriving-clear-title">Clear wardriving data?</h2><p>{clearMode === "all" ? "This removes every stored device, sighting, and session. It cannot be undone." : "This removes all sightings and session history but keeps the device catalog."}</p><div className="dialog-actions"><button className="secondary-button" onClick={() => setClearMode(null)} disabled={busy !== null}>Cancel</button><button className={clearMode === "all" ? "danger-button" : "primary-button"} onClick={() => void clearData()} disabled={busy !== null}>{busy === "clear" ? "Clearing…" : "Clear data"}</button></div></div></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WardrivingStat({ icon, label, value, detail, textValue = false }: { icon: React.ReactNode; label: string; value: number | string; detail: string; textValue?: boolean }) {
|
||||
return <article className="wardriving-stat"><span>{icon}{label}</span><strong className={textValue ? "text-value" : ""}>{value}</strong><small>{detail}</small></article>;
|
||||
}
|
||||
|
||||
function WardrivingDeviceRow({ device }: { device: WardrivingDevice }) {
|
||||
const label = device.ssid || device.displayName || "Unnamed device";
|
||||
return <article className="wardriving-device-row"><span className={`wardriving-device-icon ${device.technology}`} aria-hidden="true">{device.technology === "bluetooth" ? <Bluetooth size={19} /> : <WifiHigh size={19} />}</span><div><strong>{label}</strong><small>{device.macAddress ?? device.key} · {device.manufacturer ?? "Manufacturer unknown"}</small></div><span className="wardriving-device-meta"><b>{device.channel ?? "—"}</b><small>{new Date(device.lastSeenAt).toLocaleTimeString()}</small></span></article>;
|
||||
}
|
||||
|
||||
function WardrivingMap({ sightings }: { sightings: WardrivingSnapshot["sightings"] }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!host.current || sightings.length === 0) return;
|
||||
const map = L.map(host.current, { zoomControl: true, attributionControl: true });
|
||||
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
|
||||
const coordinates = sightings.flatMap((sighting) => sighting.latitude !== null && sighting.longitude !== null ? [L.latLng(sighting.latitude, sighting.longitude)] : []);
|
||||
for (const sighting of sightings) {
|
||||
if (sighting.latitude === null || sighting.longitude === null) continue;
|
||||
const bluetooth = sighting.technology === "bluetooth";
|
||||
const marker = L.circleMarker([sighting.latitude, sighting.longitude], { radius: bluetooth ? 5 : 6, color: "#10130f", weight: 2, fillColor: bluetooth ? "#8bc4ff" : "#b9e769", fillOpacity: 0.9 }).addTo(map);
|
||||
marker.bindTooltip(`${bluetooth ? "Bluetooth" : "WiFi"} · ${sighting.displayName || sighting.macAddress || "Device"}`);
|
||||
}
|
||||
const bounds = L.latLngBounds(coordinates);
|
||||
if (bounds.isValid() && coordinates.length > 1) map.fitBounds(bounds, { padding: [28, 28], maxZoom: 16 }); else if (coordinates[0]) map.setView(coordinates[0], 15);
|
||||
return () => { map.remove(); };
|
||||
}, [sightings]);
|
||||
if (sightings.length === 0) return <div className="wardriving-map-empty"><MapPin size={42} /><strong>No mapped sightings yet</strong><span>Start a session and keep the paired phone's location permission active.</span></div>;
|
||||
return <div className="wardriving-map" ref={host} aria-label="Map of WiFi and Bluetooth observations" />;
|
||||
}
|
||||
@@ -130,6 +130,68 @@ export type BluetoothStatus = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type WardrivingTechnology = "wifi" | "bluetooth" | "other";
|
||||
export type WardrivingDevice = {
|
||||
id: number;
|
||||
key: string;
|
||||
technology: WardrivingTechnology;
|
||||
macAddress: string | null;
|
||||
displayName: string | null;
|
||||
ssid: string | null;
|
||||
manufacturer: string | null;
|
||||
channel: string | null;
|
||||
encryption: string | null;
|
||||
firstSeenAt: string;
|
||||
lastSeenAt: string;
|
||||
strongestSignalDbm: number | null;
|
||||
latestLatitude: number | null;
|
||||
latestLongitude: number | null;
|
||||
latestAccuracyMeters: number | null;
|
||||
};
|
||||
|
||||
export type WardrivingSighting = {
|
||||
id: number;
|
||||
sessionId: number;
|
||||
deviceId: number;
|
||||
observedAt: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
accuracyMeters: number | null;
|
||||
signalDbm: number | null;
|
||||
channel: string | null;
|
||||
source: string;
|
||||
technology: WardrivingTechnology;
|
||||
displayName: string | null;
|
||||
macAddress: string | null;
|
||||
};
|
||||
|
||||
export type WardrivingSession = {
|
||||
id: number;
|
||||
startedAt: string;
|
||||
endedAt: string | null;
|
||||
state: "running" | "stopped" | "error";
|
||||
wifiInterface: string | null;
|
||||
bluetoothInterface: string | null;
|
||||
errorMessage: string | null;
|
||||
devices: number;
|
||||
sightings: number;
|
||||
};
|
||||
|
||||
export type WardrivingSnapshot = {
|
||||
supported: boolean;
|
||||
enabled: boolean;
|
||||
updatedAt: string;
|
||||
running: boolean;
|
||||
kismet: { available: boolean; running: boolean; version: string | null; message: string };
|
||||
session: WardrivingSession | null;
|
||||
gps: { available: boolean; fix: { receivedAt: string; capturedAt: string; latitude: number; longitude: number; accuracyMeters: number; ageSeconds: number } | null; message: string };
|
||||
sources: { wifiInterface: string | null; bluetoothInterface: string | null; wifiPassive: true; bluetoothMode: "discoverable-metadata"; noPairing: true };
|
||||
statistics: { devices: number; wifiDevices: number; bluetoothDevices: number; sightings: number; mappedSightings: number; sessions: number; lastSeenAt: string | null };
|
||||
devices: WardrivingDevice[];
|
||||
sightings: WardrivingSighting[];
|
||||
recentSessions: WardrivingSession[];
|
||||
};
|
||||
|
||||
export type TripSummary = {
|
||||
id: number;
|
||||
deviceId: string;
|
||||
@@ -318,6 +380,18 @@ export async function getBluetoothStatus(): Promise<BluetoothStatus> {
|
||||
return parseResponse<BluetoothStatus>(await fetch("/api/mobile/bluetooth", { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
export async function getWardriving(): Promise<WardrivingSnapshot> {
|
||||
return parseResponse<WardrivingSnapshot>(await fetch("/api/wardriving", { credentials: "same-origin" }));
|
||||
}
|
||||
|
||||
export async function wardrivingAction(action: "start" | "stop" | "restart", csrfToken: string): Promise<WardrivingSnapshot> {
|
||||
return post<WardrivingSnapshot>("/api/wardriving/actions", { action }, csrfToken);
|
||||
}
|
||||
|
||||
export async function clearWardriving(mode: "history" | "all", csrfToken: string): Promise<void> {
|
||||
await post("/api/wardriving/clear", { mode }, csrfToken);
|
||||
}
|
||||
|
||||
export async function getTrips(): Promise<TripSummary[]> {
|
||||
const response = await parseResponse<{ trips: TripSummary[] }>(
|
||||
await fetch("/api/trips", { credentials: "same-origin" })
|
||||
|
||||
+95
-2
@@ -258,8 +258,8 @@ button:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
.brand-compact { display: none; }
|
||||
.sidebar nav { display: flex; flex: 1; }
|
||||
.sidebar nav .nav-item:disabled { display: none; }
|
||||
.nav-item { width: 72px; min-height: 56px; }
|
||||
.nav-item.logout { margin: 0 0 0 auto; }
|
||||
.nav-item { width: auto; min-width: 0; flex: 1; min-height: 56px; }
|
||||
.nav-item.logout { flex: 0 0 48px; margin: 0 0 0 auto; }
|
||||
.dashboard { padding: 26px 18px; }
|
||||
.dashboard-header { align-items: flex-start; }
|
||||
.connection-state { padding: 0; }
|
||||
@@ -297,6 +297,99 @@ button:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
.icon-button:hover { color: var(--text); background: var(--surface-raised); }
|
||||
.icon-button:active { transform: scale(0.96); }
|
||||
|
||||
.status-success { display: flex; align-items: center; gap: 10px; padding: 13px 16px; color: var(--accent); background: rgba(185, 231, 105, 0.07); border: 1px solid rgba(185, 231, 105, 0.25); border-radius: 10px; }
|
||||
|
||||
.wardriving-page { display: grid; gap: 18px; min-width: 0; }
|
||||
.wardriving-hero { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 28px; align-items: center; min-height: 210px; padding: clamp(24px, 3.5vw, 42px); overflow: hidden; background: radial-gradient(circle at 14% 20%, rgba(185, 231, 105, 0.13), transparent 35%), radial-gradient(circle at 90% 86%, rgba(139, 196, 255, 0.08), transparent 28%), var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
|
||||
.wardriving-hero-copy { min-width: 0; max-width: 720px; }
|
||||
.wardriving-kicker { display: flex; align-items: center; gap: 8px; margin-bottom: 15px; color: var(--accent); font: 700 .73rem/1.2 ui-monospace, "Cascadia Code", monospace; letter-spacing: .1em; text-transform: uppercase; }
|
||||
.wardriving-hero h2 { max-width: 680px; margin: 0 0 13px; font-size: clamp(1.8rem, 3vw, 3.1rem); line-height: 1.02; letter-spacing: -.055em; text-wrap: balance; }
|
||||
.wardriving-hero p { max-width: 650px; margin: 0; color: var(--muted); line-height: 1.55; }
|
||||
.wardriving-session-state { display: flex; align-items: center; gap: 12px; min-width: 190px; padding: 14px 16px; background: #121610; border: 1px solid var(--line); border-radius: 11px; }
|
||||
.wardriving-session-state > div { display: grid; gap: 5px; }
|
||||
.wardriving-session-state strong { font-size: .86rem; }
|
||||
.wardriving-session-state small { color: var(--muted); font-size: .7rem; line-height: 1.35; }
|
||||
.wardriving-pulse { width: 12px; height: 12px; flex: none; border-radius: 50%; background: #7d8779; }
|
||||
.wardriving-session-state.is-running .wardriving-pulse { background: var(--accent); box-shadow: 0 0 0 7px rgba(185, 231, 105, .1); animation: wardriving-pulse 1.8s ease-in-out infinite; }
|
||||
@keyframes wardriving-pulse { 50% { box-shadow: 0 0 0 12px rgba(185, 231, 105, 0); } }
|
||||
.wardriving-actions { display: flex; flex-wrap: wrap; gap: 10px; justify-content: flex-end; }
|
||||
.wardriving-actions .primary-button, .wardriving-actions .danger-button { min-width: 160px; }
|
||||
.wardriving-empty { display: grid; justify-items: center; gap: 10px; padding: 44px 24px; color: var(--muted); background: var(--surface); border: 1px dashed #52614d; border-radius: var(--radius); text-align: center; }
|
||||
.wardriving-empty svg { color: var(--accent); }
|
||||
.wardriving-empty h2 { margin: 0; color: var(--text); }
|
||||
.wardriving-empty p { max-width: 620px; margin: 0; line-height: 1.55; }
|
||||
.wardriving-empty code, .wardriving-note code { color: var(--text); font-family: ui-monospace, "Cascadia Code", monospace; }
|
||||
.wardriving-stat-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
|
||||
.wardriving-stat { min-width: 0; display: grid; gap: 9px; padding: 20px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
|
||||
.wardriving-stat > span { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: .78rem; }
|
||||
.wardriving-stat > span svg { color: var(--accent); }
|
||||
.wardriving-stat strong { overflow: hidden; font: 750 2rem/1 ui-monospace, "Cascadia Code", monospace; letter-spacing: -.07em; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.wardriving-stat strong.text-value { font-size: 1.35rem; letter-spacing: -.04em; }
|
||||
.wardriving-stat small { min-height: 2.5em; overflow: hidden; color: var(--muted); font-size: .72rem; line-height: 1.35; text-overflow: ellipsis; }
|
||||
.wardriving-workspace { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(390px, .75fr); gap: 18px; align-items: stretch; }
|
||||
.wardriving-map-panel, .wardriving-devices-panel, .wardriving-source-panel { min-width: 0; overflow: hidden; padding: 24px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
|
||||
.wardriving-panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; }
|
||||
.wardriving-panel-heading h2 { margin: 0 0 6px; font-size: 1.2rem; }
|
||||
.wardriving-panel-heading p { margin: 0; color: var(--muted); font-size: .78rem; line-height: 1.4; }
|
||||
.wardriving-map-legend { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: .7rem; white-space: nowrap; }
|
||||
.wardriving-map-legend i { width: 9px; height: 9px; display: inline-block; border-radius: 50%; background: var(--accent); }
|
||||
.wardriving-map-legend i.bluetooth { margin-left: 6px; background: #8bc4ff; }
|
||||
.wardriving-map { min-height: 480px; overflow: hidden; border-radius: 10px; background: #c9d4c2; }
|
||||
.wardriving-map .leaflet-control-attribution { font-size: 9px; }
|
||||
.wardriving-map-empty { min-height: 480px; display: grid; place-content: center; justify-items: center; gap: 9px; padding: 24px; color: var(--muted); background: #121610; border: 1px solid var(--line); border-radius: 10px; text-align: center; }
|
||||
.wardriving-map-empty svg { color: var(--accent); }
|
||||
.wardriving-map-empty strong { color: var(--text); }
|
||||
.wardriving-map-empty span { max-width: 300px; font-size: .78rem; line-height: 1.45; }
|
||||
.wardriving-filters { display: flex; gap: 4px; margin-bottom: 12px; padding: 4px; background: #121610; border: 1px solid var(--line); border-radius: 8px; }
|
||||
.wardriving-filters button { min-height: 35px; flex: 1; color: var(--muted); background: transparent; border: 0; border-radius: 6px; font-size: .74rem; font-weight: 700; cursor: pointer; }
|
||||
.wardriving-filters button:hover { color: var(--text); background: var(--surface-raised); }
|
||||
.wardriving-filters button.active { color: var(--accent-ink); background: var(--accent); }
|
||||
.wardriving-device-list { max-height: 485px; overflow: auto; }
|
||||
.wardriving-device-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; min-height: 66px; padding: 10px 3px; border-bottom: 1px solid var(--line); }
|
||||
.wardriving-device-row:last-child { border-bottom: 0; }
|
||||
.wardriving-device-icon { width: 34px; height: 34px; display: grid; place-items: center; border-radius: 9px; }
|
||||
.wardriving-device-icon.wifi { color: var(--accent); background: rgba(185, 231, 105, .09); }
|
||||
.wardriving-device-icon.bluetooth { color: #8bc4ff; background: rgba(139, 196, 255, .1); }
|
||||
.wardriving-device-row > div { min-width: 0; display: grid; gap: 5px; }
|
||||
.wardriving-device-row strong, .wardriving-device-row small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.wardriving-device-row strong { font-size: .82rem; }
|
||||
.wardriving-device-row small { color: var(--muted); font: .67rem/1.2 ui-monospace, "Cascadia Code", monospace; }
|
||||
.wardriving-device-meta { display: grid; justify-items: end; gap: 5px; }
|
||||
.wardriving-device-meta b { color: var(--text); font: 700 .72rem/1 ui-monospace, "Cascadia Code", monospace; }
|
||||
.wardriving-device-meta small { color: var(--muted); font-size: .64rem; }
|
||||
.wardriving-list-empty { min-height: 180px; display: grid; place-content: center; justify-items: center; gap: 9px; color: var(--muted); font-size: .78rem; text-align: center; }
|
||||
.wardriving-list-empty svg { color: var(--accent); }
|
||||
.wardriving-bottom-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
|
||||
.wardriving-source-panel > .wardriving-panel-heading > svg { color: var(--muted); }
|
||||
.wardriving-source-list { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin: 26px 0 0; }
|
||||
.wardriving-source-list div { display: grid; gap: 8px; min-width: 0; }
|
||||
.wardriving-source-list dt { color: var(--muted); font-size: .72rem; }
|
||||
.wardriving-source-list dd { display: flex; align-items: center; gap: 6px; min-width: 0; margin: 0; overflow: hidden; color: var(--text); font: 700 .78rem/1.2 ui-monospace, "Cascadia Code", monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.wardriving-source-list dd svg { flex: none; color: var(--accent); }
|
||||
.wardriving-note { margin: 22px 0 0; color: var(--muted); font-size: .75rem; line-height: 1.5; }
|
||||
.wardriving-clear-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 23px; }
|
||||
.wardriving-clear-actions button { min-height: 46px; }
|
||||
|
||||
@media (max-width: 1250px) {
|
||||
.wardriving-hero { grid-template-columns: minmax(0, 1fr) auto; }
|
||||
.wardriving-actions { grid-column: 1 / -1; justify-content: flex-start; }
|
||||
.wardriving-workspace { grid-template-columns: 1fr; }
|
||||
.wardriving-devices-panel { max-height: 650px; }
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.wardriving-hero { grid-template-columns: 1fr; gap: 19px; }
|
||||
.wardriving-session-state { min-width: 0; }
|
||||
.wardriving-actions { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.wardriving-actions .primary-button, .wardriving-actions .danger-button { min-width: 0; width: 100%; }
|
||||
.wardriving-stat-grid, .wardriving-bottom-grid { grid-template-columns: 1fr 1fr; }
|
||||
.wardriving-map-panel, .wardriving-devices-panel, .wardriving-source-panel { padding: 18px; }
|
||||
.wardriving-map, .wardriving-map-empty { min-height: 340px; }
|
||||
.wardriving-source-list { grid-template-columns: 1fr; }
|
||||
.wardriving-clear-actions { display: grid; }
|
||||
.wardriving-clear-actions button { width: 100%; }
|
||||
}
|
||||
|
||||
.adb-page { min-width: 0; display: grid; gap: 18px; }
|
||||
.adb-success { display: flex; align-items: center; gap: 10px; padding: 13px 16px; color: var(--accent); background: rgba(185, 231, 105, 0.07); border: 1px solid rgba(185, 231, 105, 0.25); border-radius: 10px; }
|
||||
.adb-command-grid { display: grid; grid-template-columns: minmax(300px, 0.7fr) minmax(520px, 1.3fr); gap: 18px; }
|
||||
|
||||
Reference in new issue
Block a user