#!/usr/bin/env python3 """KidAdLens Companion Local USB Device Scanner (Exact App IDs & Versions). 100% local, read-only, zero-dependency Python 3 utility for parents and researchers who want exact installed app version numbers on an iPhone, iPad, or Android/Fire tablet without MDM profiles, jailbreaks, or app installs. How it works (zero cloud upload, zero child data): - iPhone / iPad (macOS / Linux / Windows): Connect via USB and tap "Trust This Computer". Reads Apple's standard read-only installation proxy via `pymobiledevice3` or `ideviceinstaller` to list user-installed apps (`CFBundleIdentifier`, display name, and exact `CFBundleShortVersionString`). - Android / Fire Tablet: Connect via USB with USB Debugging enabled. Runs read-only `adb shell pm list packages -3` + `adb shell dumpsys package packages` to list user-installed packages and exact `versionName` / `versionCode`. Output: Writes `kidadlens_device_inventory.json` (`schema: kidadlens-device-inventory/1`) locally on your computer. Drop that file onto KidAdLens's "Rate My Kid's Device" page (https://chrisjvargo.com/kidadlens/rate-my-device.html) — all rating runs 100% locally in your browser with zero server upload. Usage: python3 kid_device_usb_scan.py # Auto-detect iOS or Android USB device python3 kid_device_usb_scan.py --ios # Scan connected iPhone / iPad python3 kid_device_usb_scan.py --android # Scan connected Android / Fire device python3 kid_device_usb_scan.py -o my_ipad.json # Custom output path """ from __future__ import annotations import argparse import json import plistlib import re import shutil import subprocess import sys from datetime import datetime, timezone from pathlib import Path from typing import Any SCHEMA = "kidadlens-device-inventory/1" PRIVACY_NOTICE = ( "Generated 100% locally on your computer. Contains only installed third-party " "app IDs, display names, and version numbers — zero child photos, device serials, " "advertising IDs, or personal telemetry." ) def utc_now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def parse_ios_pymobiledevice3_json(raw_text: str) -> list[dict[str, str]]: """Parse JSON output of `pymobiledevice3 apps list --type User`.""" data = json.loads(raw_text) items: list[dict[str, str]] = [] if isinstance(data, dict): for bundle_id, info in data.items(): if not isinstance(info, dict): continue bid = str(info.get("CFBundleIdentifier") or bundle_id or "").strip() if not bid or bid.startswith("com.apple."): continue name = str( info.get("CFBundleDisplayName") or info.get("CFBundleName") or bid ).strip() ver = str(info.get("CFBundleShortVersionString") or "").strip() build = str(info.get("CFBundleVersion") or "").strip() items.append({ "store_id": bid, "name": name, "version": ver or build, "build": build, }) elif isinstance(data, list): for info in data: if not isinstance(info, dict): continue bid = str(info.get("CFBundleIdentifier") or info.get("bundle_id") or "").strip() if not bid or bid.startswith("com.apple."): continue name = str(info.get("CFBundleDisplayName") or info.get("CFBundleName") or bid).strip() ver = str(info.get("CFBundleShortVersionString") or "").strip() build = str(info.get("CFBundleVersion") or "").strip() items.append({ "store_id": bid, "name": name, "version": ver or build, "build": build, }) items.sort(key=lambda x: (x["name"].lower(), x["store_id"].lower())) return items def parse_ios_ideviceinstaller_xml(raw_bytes: bytes) -> list[dict[str, str]]: """Parse XML plist output of `ideviceinstaller -l -o xml`.""" parsed = plistlib.loads(raw_bytes) rows = parsed if isinstance(parsed, list) else list(parsed.values()) if isinstance(parsed, dict) else [] items: list[dict[str, str]] = [] for info in rows: if not isinstance(info, dict): continue if str(info.get("ApplicationType") or "").lower() == "system": continue bid = str(info.get("CFBundleIdentifier") or "").strip() if not bid or bid.startswith("com.apple."): continue name = str(info.get("CFBundleDisplayName") or info.get("CFBundleName") or bid).strip() ver = str(info.get("CFBundleShortVersionString") or "").strip() build = str(info.get("CFBundleVersion") or "").strip() items.append({ "store_id": bid, "name": name, "version": ver or build, "build": build, }) items.sort(key=lambda x: (x["name"].lower(), x["store_id"].lower())) return items def parse_android_dumpsys(dumpsys_text: str, user_packages: set[str] | None = None) -> list[dict[str, str]]: """Parse `adb shell dumpsys package packages` filtered to user-installed packages.""" pkg_re = re.compile(r"^\s*Package\s+\[([A-Za-z0-9._-]+)\]") vname_re = re.compile(r"\bversionName=([^\s]+)") vcode_re = re.compile(r"\bversionCode=(\d+)") by_pkg: dict[str, dict[str, str]] = {} cur_pkg: str | None = None for line in dumpsys_text.splitlines(): m_pkg = pkg_re.match(line) if m_pkg: cur_pkg = m_pkg.group(1).strip() if user_packages is None or cur_pkg in user_packages: by_pkg.setdefault(cur_pkg, { "store_id": cur_pkg, "name": cur_pkg, "version": "", "build": "", }) else: cur_pkg = None continue if not cur_pkg: continue rec = by_pkg[cur_pkg] if not rec["version"]: mv = vname_re.search(line) if mv: rec["version"] = mv.group(1).strip().strip('"') if not rec["build"]: mc = vcode_re.search(line) if mc: rec["build"] = mc.group(1).strip() if user_packages: for pkg in user_packages: by_pkg.setdefault(pkg, {"store_id": pkg, "name": pkg, "version": "", "build": ""}) return sorted(by_pkg.values(), key=lambda x: x["store_id"].lower()) def _run_cmd(cmd: list[str], *, timeout: int = 30) -> subprocess.CompletedProcess[bytes]: return subprocess.run(cmd, capture_output=True, timeout=timeout, check=False) def scan_ios_usb() -> tuple[list[dict[str, str]], str]: """Read user-installed iOS/iPadOS apps + exact versions over USB (read-only).""" if shutil.which("pymobiledevice3"): cp = _run_cmd(["pymobiledevice3", "apps", "list", "--type", "User"], timeout=45) if cp.returncode == 0 and cp.stdout.strip(): return parse_ios_pymobiledevice3_json(cp.stdout.decode("utf-8", errors="replace")), "pymobiledevice3" if shutil.which("ideviceinstaller"): cp = _run_cmd(["ideviceinstaller", "-l", "-o", "xml"], timeout=45) if cp.returncode == 0 and cp.stdout.strip(): return parse_ios_ideviceinstaller_xml(cp.stdout), "ideviceinstaller" raise RuntimeError( "No connected iPhone/iPad found or helper missing. Install `pymobiledevice3` " "(`pip install pymobiledevice3`) or `ideviceinstaller`, connect via USB, and tap 'Trust This Computer'." ) def scan_android_usb() -> tuple[list[dict[str, str]], str]: """Read third-party Android/Fire packages + exact versions via read-only ADB.""" adb = shutil.which("adb") if not adb: raise RuntimeError("`adb` not found in PATH. Install Android Platform Tools to scan Android over USB.") cp_dev = _run_cmd([adb, "devices"], timeout=10) lines = [ ln.strip() for ln in cp_dev.stdout.decode("utf-8", errors="replace").splitlines()[1:] if ln.strip() and "\tdevice" in ln ] if not lines: raise RuntimeError( "No authorized Android device detected via USB. Enable USB Debugging and accept the classifier criteria on the device." ) cp_pm = _run_cmd([adb, "shell", "pm", "list", "packages", "-3"], timeout=20) if cp_pm.returncode != 0: raise RuntimeError(f"adb pm list failed: {cp_pm.stderr.decode('utf-8', errors='replace').strip()}") user_pkgs = { ln.split(":", 1)[1].strip() for ln in cp_pm.stdout.decode("utf-8", errors="replace").splitlines() if ln.strip().startswith("package:") } cp_dump = _run_cmd([adb, "shell", "dumpsys", "package", "packages"], timeout=45) dump_text = cp_dump.stdout.decode("utf-8", errors="replace") if cp_dump.returncode == 0 else "" return parse_android_dumpsys(dump_text, user_packages=user_pkgs), "adb" def build_inventory_payload(platform: str, apps: list[dict[str, str]], method: str) -> dict[str, Any]: return { "schema": SCHEMA, "scanned_utc": utc_now(), "platform": platform, "scan_method": method, "privacy_notice": PRIVACY_NOTICE, "app_count": len(apps), "apps": apps, } def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser( description="Read-only local USB app & exact-version scanner for KidAdLens Rate My Kid's Device." ) grp = ap.add_mutually_exclusive_group() grp.add_argument("--ios", action="store_true", help="Scan a USB-connected iPhone or iPad (pymobiledevice3 / ideviceinstaller)") grp.add_argument("--android", action="store_true", help="Scan a USB-connected Android or Fire device (adb)") grp.add_argument("--auto", action="store_true", help="Auto-detect connected iOS or Android USB device (default)") ap.add_argument("-o", "--output", default="kidadlens_device_inventory.json", help="Output JSON file path") args = ap.parse_args(argv) platform = "" apps: list[dict[str, str]] = [] method = "" errors: list[str] = [] if args.ios: apps, method = scan_ios_usb() platform = "ios" elif args.android: apps, method = scan_android_usb() platform = "android" else: for plat_try, fn in (("ios", scan_ios_usb), ("android", scan_android_usb)): try: apps, method = fn() platform = plat_try break except Exception as exc: errors.append(f"{plat_try}: {exc}") if not platform: print("ERROR: Could not detect a USB-connected iOS or Android device:", file=sys.stderr) for err in errors: print(f" - {err}", file=sys.stderr) return 2 payload = build_inventory_payload(platform, apps, method) out_path = Path(args.output) out_path.write_text(json.dumps(payload, indent=2, sort_keys=False) + "\n", encoding="utf-8") print(f"Scanned {len(apps)} {platform.upper()} apps with exact versions via {method} -> {out_path}") print("Next step: drop this file onto https://chrisjvargo.com/kidadlens/rate-my-device.html (100% local in browser).") return 0 if __name__ == "__main__": raise SystemExit(main())