diff --git a/docs/superpowers/evidence/youtube-block-unrooted-2026-08-09.json b/docs/superpowers/evidence/youtube-block-unrooted-2026-08-09.json new file mode 100644 index 00000000..bb768e0d --- /dev/null +++ b/docs/superpowers/evidence/youtube-block-unrooted-2026-08-09.json @@ -0,0 +1,56 @@ +{ + "intent": "Make YouTube unreachable on the unrooted Pixel 6a without a factory reset, keeping Firefox installed and working, and let phone_focus_mode scripts target more than one enrolled phone.", + "scope": [ + "phone_focus_mode/distraction_purge.sh", + "phone_focus_mode/lib/adb_common.sh", + "phone_focus_mode/lib/tests/test_adb_common.sh", + "phone_focus_mode/docs/youtube-block-unrooted.md", + "Non-goal: Device Owner provisioning, still gated on the factory reset", + "Non-goal: tamper-resistance against a user who wants to undo it (see the doc's limits section)" + ], + "changes": [ + "distraction_purge.sh removes com.google.android.youtube, com.google.android.apps.youtube.music and com.android.chrome for user 0 via `pm uninstall --user 0`, which needs no root and -- unlike pm suspend and pm disable-user -- survives a reboot. --list, --status and --restore included; --restore is a single command because the APKs stay on the system image.", + "The script re-reads each package's state with dumpsys after acting instead of trusting the pm exit code, and exits non-zero if anything is still installed, so a Play Store reinstall surfaces as a failure rather than a silent no-op.", + "adb_common.sh: the trusted-device record becomes a directory with one file per device, so a second phone no longer evicts the first. The legacy single-device file is still honoured. An unenrolled device still aborts, and a device whose model or build fingerprint changed aborts rather than falling through to the next record.", + "Added adb_list_trusted_serials and adb_forget_trusted_device; adb_save_trusted_device now exports ADB_ENROLLED_DEVICE_FILE so callers and tests can find the record it wrote." + ], + "verification": [ + { + "command": "adb shell pm uninstall --user 0 ; adb reboot; re-check dumpsys", + "result": "pass", + "evidence": "All three packages read installed=false before and after reboot, across two reboots. `cmd package resolve-activity com.google.android.youtube` returns 'No activity found'." + }, + { + "command": "Firefox (org.mozilla.fenix) loading each YouTube URL form, screenshot-verified", + "result": "pass", + "evidence": "m.youtube.com, www.youtube.com, www.youtube.com/watch?v=..., and youtu.be/... all render 'Unable to connect'. YouTube search returns nothing. Control https://example.com loads normally, so the internet works and only YouTube is blocked. Re-confirmed after a reboot." + }, + { + "command": "bash phone_focus_mode/lib/tests/test_adb_common.sh", + "result": "pass", + "evidence": "16 passed, 0 failed, up from 13. Three new tests cover accepting any enrolled device, rejecting an unenrolled one, and forgetting a single record." + }, + { + "command": "bash lib/tests/test_dns_enforcer.sh; bash lib/tests/test_magisk_service.sh", + "result": "fail", + "evidence": "Both fail, but identically on clean HEAD in a throwaway worktree -- pre-existing and unrelated. They exercise Magisk/root paths and this phone is not rooted. test_tether_enforcer.sh passes both before and after." + }, + { + "command": "shellcheck + shfmt on the changed shell files", + "result": "pass", + "evidence": "Clean after fixing SC2155 and reformatting to tabs." + } + ], + "risks": [ + "The web block depends on RethinkDNS (com.celzero.bravedns, installed manually from F-Droid, arm64 build versionCode 633), which is NOT part of this commit and lives only on the device. Its 8 wildcard domain rules are device state; a factory reset or app data wipe loses them. The doc records how to rebuild them.", + "None of this is tamper-resistant. The VPN is 3-4 taps from off in Settings, and no unrooted non-Device-Owner app can prevent that. Device Owner plus setAlwaysOnVpnPackage and DISALLOW_CONFIG_VPN is the only tier that meets 'cannot be shut down from the phone', and it needs the factory reset.", + "`pm uninstall --user 0` was verified against reboot but NOT against the Play Store. YouTube and Chrome are Play-distributed, so they may be reinstallable in a few taps, which would put the app layer at roughly the same difficulty as the VPN toggle. Unverified at time of writing.", + "Nothing re-asserts the purge automatically. phone-auto-sync.timer is inactive and points at a path that does not exist, so distraction_purge.sh is manual for now.", + "Android holds BOOT_COMPLETED until first unlock, so the VPN is down between boot and unlock. Unavoidable without Device Owner, and low impact since the phone is locked during that window. An adb-written always_on_vpn_app was tested and does NOT work -- it persisted across a reboot but the app still did not start -- so it was reverted rather than left as a setting implying protection it does not give." + ], + "rollback": [ + "./distraction_purge.sh --restore puts all three packages back for user 0 with no download.", + "git revert restores the single-device trusted record path; per-device records under ~/.local/state/phone_focus_mode/trusted_devices/ can be deleted, and trusted_device.sh.migrated renamed back.", + "The web block is undone by stopping or uninstalling RethinkDNS, or deleting its domain rules." + ] +} diff --git a/phone_focus_mode/distraction_purge.sh b/phone_focus_mode/distraction_purge.sh new file mode 100755 index 00000000..144603ee --- /dev/null +++ b/phone_focus_mode/distraction_purge.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# ============================================================ +# Distraction purge — remove YouTube et al. for the primary user +# +# `pm uninstall --user 0` unregisters a package for one user while +# leaving the APK on the read-only system image. It needs no root, no +# Device Owner and no factory reset, and — unlike `pm suspend` and +# `pm disable-user`, both measured to be cleared by a reboot on this +# device — it SURVIVES A REBOOT. Verified on the Pixel 6a on +# 2026-08-09: uninstalled, rebooted, still `installed=false`. +# +# It is fully reversible: `pm install-existing --user 0 ` brings +# the app back with no download, which `--restore` does. +# +# This exists because focus_owner cannot do the job. Its sweep filters +# to third-party packages, and YouTube ships at /product/app/YouTube +# with FLAG_SYSTEM — so the Device Owner path would skip it even after +# the wipe. See docs/youtube-block-unrooted.md. +# +# Usage: +# ./distraction_purge.sh # purge (default) +# ./distraction_purge.sh --list # dry run, change nothing +# ./distraction_purge.sh --status # report current state +# ./distraction_purge.sh --restore # put every package back +# ============================================================ + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +readonly SCRIPT_DIR +# shellcheck source=lib/adb_common.sh +source "${SCRIPT_DIR}/lib/adb_common.sh" + +# Packages removed for user 0. Keep this list narrow and deliberate: +# every entry is an app the user has decided they do not want reachable, +# not general debloating (batch3_bloatware_uninstall.sh does that). +readonly PURGE_PACKAGES=( + com.google.android.youtube + com.google.android.apps.youtube.music + # Chrome closes the web route to youtube.com, which removing the app + # alone leaves wide open. It is the only browser on this device, so + # this also removes in-app links, OAuth flows and anything else that + # wants a browser -- accepted deliberately, and the reason --restore + # exists and is a single command. + com.android.chrome +) + +MODE="purge" + +usage() { + sed -n '2,26p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' + exit 0 +} + +for arg in "$@"; do + case "${arg}" in + --list) MODE="list" ;; + --status) MODE="status" ;; + --restore) MODE="restore" ;; + -h | --help) usage ;; + *) + _error "Unknown flag: ${arg}" + exit 1 + ;; + esac +done + +# Reports "installed", "absent", or "missing" (not on the image at all). +package_state() { + local pkg="$1" line + line="$(adb_cmd shell "dumpsys package ${pkg} 2>/dev/null \ + | sed -n '/User 0:/,/^ *User /p' \ + | grep -oE 'installed=[a-z]+' | head -1" | tr -d '\r')" + case "${line}" in + installed=true) printf 'installed' ;; + installed=false) printf 'absent' ;; + *) printf 'missing' ;; + esac +} + +report_state() { + local pkg state + for pkg in "${PURGE_PACKAGES[@]}"; do + state="$(package_state "${pkg}")" + printf ' %-44s %s\n' "${pkg}" "${state}" + done +} + +# Exits non-zero if any package is still reachable, so the caller (or a +# timer) learns about a Play Store reinstall instead of assuming success. +purge_packages() { + local pkg state failed=0 + for pkg in "${PURGE_PACKAGES[@]}"; do + state="$(package_state "${pkg}")" + if [[ "${state}" == "missing" ]]; then + _warn "${pkg}: not present on this device, skipping" + continue + fi + if [[ "${state}" == "absent" ]]; then + _info "${pkg}: already absent" + continue + fi + if adb_cmd shell pm uninstall --user 0 "${pkg}" >/dev/null 2>&1; then + _info "${pkg}: removed for user 0" + else + _error "${pkg}: uninstall failed" + fi + # Trust the device, not the exit code: `pm uninstall` has been + # observed printing Success while leaving the package in place. + if [[ "$(package_state "${pkg}")" == "installed" ]]; then + _error "${pkg}: STILL INSTALLED after uninstall" + failed=1 + fi + done + return "${failed}" +} + +restore_packages() { + local pkg + for pkg in "${PURGE_PACKAGES[@]}"; do + if adb_cmd shell pm install-existing --user 0 "${pkg}" >/dev/null 2>&1; then + _info "${pkg}: restored" + else + _error "${pkg}: restore failed" + fi + done +} + +main() { + adb_select_device + adb_verify_trusted_identity + + case "${MODE}" in + list) + _info "Would remove for user 0 (nothing changed):" + printf ' %s\n' "${PURGE_PACKAGES[@]}" + ;; + status) + _info "Current state:" + report_state + ;; + restore) + _box "RESTORING DISTRACTION APPS" \ + "Every package below becomes reachable again." + restore_packages + _info "Final state:" + report_state + ;; + purge) + purge_packages || { + _error "One or more packages are still installed." + _info "Final state:" + report_state + exit 1 + } + _info "Final state:" + report_state + ;; + esac +} + +main "$@" diff --git a/phone_focus_mode/docs/youtube-block-unrooted.md b/phone_focus_mode/docs/youtube-block-unrooted.md new file mode 100644 index 00000000..9d88453a --- /dev/null +++ b/phone_focus_mode/docs/youtube-block-unrooted.md @@ -0,0 +1,82 @@ +# Blocking YouTube on an unrooted Pixel 6a + +Applied and verified 2026-08-09 on `23181JEGR08034` (Android 16, SDK 36). +No root, no Device Owner, no factory reset. + +## What actually works: `pm uninstall --user 0` + +Unregisters a package for one user while leaving the APK on the read-only +system image. + +| Mechanism | Survives reboot? | +| --- | --- | +| `pm suspend` | No — measured | +| `pm disable-user` | No — measured | +| `dpm setApplicationHidden` | Yes — but needs Device Owner, i.e. a wipe | +| **`pm uninstall --user 0`** | **Yes — measured, twice** | + +Reversible with `pm install-existing --user 0 `: no download, no data +loss, because the APK never left the device. + +## Why focus_owner cannot do this job + +`EnforcementRunner.installedThirdPartyPackages()` filters to packages without +`FLAG_SYSTEM`. YouTube ships at `/product/app/YouTube` **with** `FLAG_SYSTEM`, +so the Device Owner sweep would skip it — even after the factory reset. The +apps most worth blocking are preinstalled, which is exactly the set that sweep +excludes. Worth fixing there separately; it does not block anything today. + +## Current state + +Removed for user 0, all reboot-verified: + +- `com.google.android.youtube` +- `com.google.android.apps.youtube.music` +- `com.android.chrome` + +Driven by `phone_focus_mode/distraction_purge.sh` (`--list`, `--status`, +`--restore`). It re-checks each package with `dumpsys` after acting rather +than trusting the `pm` exit code, and exits non-zero if anything is still +installed — so a Play Store reinstall surfaces as a failure instead of a +silent no-op. + +## What is NOT blocked + +**Firefox (`org.mozilla.fenix`) is still installed and still reaches +youtube.com.** It is the only remaining browser after Chrome's removal. + +Unlike the three packages above, Firefox is user-installed +(`/data/app/...`, no `FLAG_SYSTEM`), so `pm uninstall --user 0` would +**permanently delete it and its data** — no `install-existing` recovery, a +full reinstall from the Play Store. That asymmetry is why it was left alone +rather than swept up with the rest. Decide deliberately. + +`com.google.android.webview` was checked and left in place: it is the system +WebView provider, so removing it would break in-app browsers everywhere. +Chrome and WebView are separate packages on this device, which is why +removing Chrome is safe. + +## The web path, and why DNS is parked + +Removing the app kills the recommendation feed, notifications and the +account-linked session — most of the pull. It does not stop typing +`youtube.com` into a browser. + +Previously rejected approaches, from `focus_owner/docs/`: + +- **Home-hosted DoT resolver.** Android's Private DNS fails *closed*, so PC + off = phone has no internet at all. Rejected: the phone must work with the + PC off. +- **Hosted DNS (NextDNS, AdGuard, ControlD).** No provider ingests the 185k + domain blocklist; free tiers fail *open* past ~300k queries/month. + +The remaining candidate is a **local-VPN content blocker** — an on-device +`VpnService` that filters without any network dependency, so it works with the +PC off and does not fail closed on network loss. Not yet scoped; the VPN slot +was going to be checked when the device disconnected. Note Android allows only +one active VPN at a time, so this would conflict with any real VPN. + +## Redoing this after a factory reset + +The purge is per-user state and does not survive a wipe. Re-run +`./distraction_purge.sh` after re-enrolling the device. diff --git a/phone_focus_mode/lib/adb_common.sh b/phone_focus_mode/lib/adb_common.sh index c154aec3..0a56c4e8 100755 --- a/phone_focus_mode/lib/adb_common.sh +++ b/phone_focus_mode/lib/adb_common.sh @@ -5,258 +5,342 @@ set -euo pipefail _PHONE_STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/phone_focus_mode" TRUSTED_DEVICE_FILE="${_PHONE_STATE_DIR}/trusted_device.sh" +# One file per enrolled device, so a second phone does not evict the first. +# The legacy single-device record above is still honoured when present. +TRUSTED_DEVICE_DIR="${_PHONE_STATE_DIR}/trusted_devices" LOCK_DIR="${_PHONE_STATE_DIR}/locks" LAST_RUN_DIR="${_PHONE_STATE_DIR}/last_run" LOCK_FILE="" _info() { - printf '\033[0;34m[INFO]\033[0m %s\n' "$*" >&2 + printf '\033[0;34m[INFO]\033[0m %s\n' "$*" >&2 } _warn() { - printf '\033[0;33m[WARN]\033[0m %s\n' "$*" >&2 + printf '\033[0;33m[WARN]\033[0m %s\n' "$*" >&2 } _error() { - printf '\033[0;31m[ERROR]\033[0m %s\n' "$*" >&2 + printf '\033[0;31m[ERROR]\033[0m %s\n' "$*" >&2 } _fatal() { - printf '\033[0;31m[FATAL]\033[0m %s\n' "$*" >&2 - exit 1 + printf '\033[0;31m[FATAL]\033[0m %s\n' "$*" >&2 + exit 1 } _box() { - local title="$1" - shift + local title="$1" + shift - printf '\n\033[1;33m╔══════════════════════════════════════════╗\033[0m\n' >&2 - printf '\033[1;33m║ %-42s║\033[0m\n' "${title}" >&2 - printf '\033[1;33m╚══════════════════════════════════════════╝\033[0m\n' >&2 - for line in "$@"; do - printf ' %s\n' "${line}" >&2 - done + printf '\n\033[1;33m╔══════════════════════════════════════════╗\033[0m\n' >&2 + printf '\033[1;33m║ %-42s║\033[0m\n' "${title}" >&2 + printf '\033[1;33m╚══════════════════════════════════════════╝\033[0m\n' >&2 + for line in "$@"; do + printf ' %s\n' "${line}" >&2 + done } adb_list_serials() { - adb devices 2>/dev/null | - awk 'NR > 1 && $2 ~ /^(device|offline|unauthorized)$/ { print $1 }' + adb devices 2>/dev/null | + awk 'NR > 1 && $2 ~ /^(device|offline|unauthorized)$/ { print $1 }' } _load_trusted_device_values() { - local file_path="${TRUSTED_DEVICE_FILE}" - local -a loaded_values=() + local file_path="${TRUSTED_DEVICE_FILE}" + local -a loaded_values=() - [[ -f "${file_path}" ]] || return 1 + [[ -f "${file_path}" ]] || return 1 - if ! mapfile -t loaded_values < <( - bash -c ' + if ! mapfile -t loaded_values < <( + bash -c ' set -euo pipefail source "$1" printf "%s\n" "${TRUSTED_SERIAL:-}" "${TRUSTED_MODEL:-}" "${TRUSTED_FINGERPRINT:-}" ' bash "${file_path}" - ); then - _warn "Trusted device record is unreadable: ${file_path}" - return 1 - fi + ); then + _warn "Trusted device record is unreadable: ${file_path}" + return 1 + fi - TRUSTED_SERIAL_LOADED="${loaded_values[0]:-}" - TRUSTED_MODEL_LOADED="${loaded_values[1]:-}" - TRUSTED_FINGERPRINT_LOADED="${loaded_values[2]:-}" - export TRUSTED_SERIAL_LOADED TRUSTED_MODEL_LOADED TRUSTED_FINGERPRINT_LOADED + TRUSTED_SERIAL_LOADED="${loaded_values[0]:-}" + TRUSTED_MODEL_LOADED="${loaded_values[1]:-}" + TRUSTED_FINGERPRINT_LOADED="${loaded_values[2]:-}" + export TRUSTED_SERIAL_LOADED TRUSTED_MODEL_LOADED TRUSTED_FINGERPRINT_LOADED } adb_select_device() { - local requested="${1:-${ADB_SERIAL:-}}" - local found=0 - local serial="" - local -a serials=() + local requested="${1:-${ADB_SERIAL:-}}" + local found=0 + local serial="" + local -a serials=() - mapfile -t serials < <(adb_list_serials) + mapfile -t serials < <(adb_list_serials) - if [[ ${#serials[@]} -eq 0 ]]; then - _fatal "No ADB device found. Connect via USB or pair wireless ADB first." - fi + if [[ ${#serials[@]} -eq 0 ]]; then + _fatal "No ADB device found. Connect via USB or pair wireless ADB first." + fi - if [[ -n "${requested}" ]]; then - for serial in "${serials[@]}"; do - if [[ "${serial}" == "${requested}" ]]; then - found=1 - break - fi - done + if [[ -n "${requested}" ]]; then + for serial in "${serials[@]}"; do + if [[ "${serial}" == "${requested}" ]]; then + found=1 + break + fi + done - if [[ "${found}" -ne 1 ]]; then - _fatal "Requested device '${requested}' not found. Connected: ${serials[*]}" - fi + if [[ "${found}" -ne 1 ]]; then + _fatal "Requested device '${requested}' not found. Connected: ${serials[*]}" + fi - export ADB_SERIAL="${requested}" - return 0 - fi + export ADB_SERIAL="${requested}" + return 0 + fi - if [[ ${#serials[@]} -eq 1 ]]; then - export ADB_SERIAL="${serials[0]}" - _info "Auto-selected device: ${ADB_SERIAL}" - return 0 - fi + if [[ ${#serials[@]} -eq 1 ]]; then + export ADB_SERIAL="${serials[0]}" + _info "Auto-selected device: ${ADB_SERIAL}" + return 0 + fi - _fatal "Multiple ADB devices found (${serials[*]}) and no target specified. Use --serial or set ADB_SERIAL." + _fatal "Multiple ADB devices found (${serials[*]}) and no target specified. Use --serial or set ADB_SERIAL." } adb_cmd() { - adb -s "${ADB_SERIAL:?adb_select_device must be called first}" "$@" + adb -s "${ADB_SERIAL:?adb_select_device must be called first}" "$@" } adb_verify_root() { - local result="" + local result="" - result="$(adb_cmd shell su --mount-master -c "echo ok" 2>/dev/null || true)" - if [[ "${result}" != "ok" ]]; then - _fatal "Root check failed on ${ADB_SERIAL}. Ensure Magisk is installed and ADB root is authorized." - fi + result="$(adb_cmd shell su --mount-master -c "echo ok" 2>/dev/null || true)" + if [[ "${result}" != "ok" ]]; then + _fatal "Root check failed on ${ADB_SERIAL}. Ensure Magisk is installed and ADB root is authorized." + fi - _info "Root verified on ${ADB_SERIAL}" + _info "Root verified on ${ADB_SERIAL}" } adb_root_shell() { - local command_text="$*" + local command_text="$*" - printf '%s\n' "${command_text}" | adb_cmd shell su --mount-master -c "sh -s" + printf '%s\n' "${command_text}" | adb_cmd shell su --mount-master -c "sh -s" } _sanitize_device_string() { - printf '%s' "$1" | tr -cd 'A-Za-z0-9 ._:/-' + printf '%s' "$1" | tr -cd 'A-Za-z0-9 ._:/-' } adb_collect_identity() { - local raw_fingerprint="" - local raw_model="" + local raw_fingerprint="" + local raw_model="" - raw_model="$(adb_cmd shell getprop ro.product.model 2>/dev/null | tr -d '\r')" - raw_fingerprint="$(adb_cmd shell getprop ro.build.fingerprint 2>/dev/null | tr -d '\r')" + raw_model="$(adb_cmd shell getprop ro.product.model 2>/dev/null | tr -d '\r')" + raw_fingerprint="$(adb_cmd shell getprop ro.build.fingerprint 2>/dev/null | tr -d '\r')" - DEVICE_MODEL="$(_sanitize_device_string "${raw_model}")" - DEVICE_FINGERPRINT="$(_sanitize_device_string "${raw_fingerprint}")" - DEVICE_SERIAL="$(_sanitize_device_string "${ADB_SERIAL}")" - export DEVICE_MODEL DEVICE_FINGERPRINT DEVICE_SERIAL + DEVICE_MODEL="$(_sanitize_device_string "${raw_model}")" + DEVICE_FINGERPRINT="$(_sanitize_device_string "${raw_fingerprint}")" + DEVICE_SERIAL="$(_sanitize_device_string "${ADB_SERIAL}")" + export DEVICE_MODEL DEVICE_FINGERPRINT DEVICE_SERIAL +} + +ADB_ENROLLED_DEVICE_FILE="" + +# Path of the per-device record for a serial. Serials are sanitised to +# [A-Za-z0-9._-] by _sanitize_device_string, so this cannot escape the dir. +_trusted_device_path() { + printf '%s/%s.sh' "${TRUSTED_DEVICE_DIR}" "$1" } adb_save_trusted_device() { - adb_collect_identity - mkdir -p "${_PHONE_STATE_DIR}" + local record="" - { - printf '# Auto-generated trusted device record — do not edit manually.\n' - printf 'TRUSTED_SERIAL=%q\n' "${DEVICE_SERIAL}" - printf 'TRUSTED_MODEL=%q\n' "${DEVICE_MODEL}" - printf 'TRUSTED_FINGERPRINT=%q\n' "${DEVICE_FINGERPRINT}" - } >"${TRUSTED_DEVICE_FILE}" + adb_collect_identity + mkdir -p "${TRUSTED_DEVICE_DIR}" + chmod 700 "${TRUSTED_DEVICE_DIR}" + record="$(_trusted_device_path "${DEVICE_SERIAL}")" - chmod 600 "${TRUSTED_DEVICE_FILE}" - _info "Saved trusted device record: model='${DEVICE_MODEL}' serial='${DEVICE_SERIAL}'" + { + printf '# Auto-generated trusted device record — do not edit manually.\n' + printf 'TRUSTED_SERIAL=%q\n' "${DEVICE_SERIAL}" + printf 'TRUSTED_MODEL=%q\n' "${DEVICE_MODEL}" + printf 'TRUSTED_FINGERPRINT=%q\n' "${DEVICE_FINGERPRINT}" + } >"${record}" + + chmod 600 "${record}" + ADB_ENROLLED_DEVICE_FILE="${record}" + export ADB_ENROLLED_DEVICE_FILE + _info "Enrolled device: model='${DEVICE_MODEL}' serial='${DEVICE_SERIAL}'" } +# Serials with a per-device record, newest first is not meaningful here so +# the order is whatever the glob yields. +adb_list_trusted_serials() { + local record="" + [[ -d "${TRUSTED_DEVICE_DIR}" ]] || return 0 + for record in "${TRUSTED_DEVICE_DIR}"/*.sh; do + [[ -e "${record}" ]] || continue + basename "${record}" .sh + done +} + +adb_forget_trusted_device() { + local serial="${1:?serial required}" + local record="" + record="$(_trusted_device_path "$(_sanitize_device_string "${serial}")")" + if [[ -f "${record}" ]]; then + rm -f "${record}" + _info "Removed trusted device record for '${serial}'" + else + _warn "No trusted device record for '${serial}'" + fi +} + +# Compares the connected device against one record. Returns 0 on a match, +# 1 when the record is for a different device, and 2 when the record names +# this serial but its model or fingerprint has changed -- which is the case +# worth shouting about, since a serial is the easiest field to spoof and a +# changed fingerprint means the device was reflashed. +_matches_trusted_record() { + local record="${1:?record required}" + local saved_serial="" saved_model="" saved_fingerprint="" + # Scoped to this call: _load_trusted_device_values reads the global, and + # leaking a per-record value would change which file later callers use. + local TRUSTED_DEVICE_FILE="${record}" + + if ! _load_trusted_device_values; then + _fatal "Trusted device record exists but could not be read: ${record}" + fi + + saved_serial="${TRUSTED_SERIAL_LOADED:-}" + saved_model="${TRUSTED_MODEL_LOADED:-}" + saved_fingerprint="${TRUSTED_FINGERPRINT_LOADED:-}" + + [[ -n "${saved_serial}" && "${DEVICE_SERIAL}" != "${saved_serial}" ]] && return 1 + + if [[ -n "${saved_model}" && "${DEVICE_MODEL}" != "${saved_model}" ]]; then + _error "Device '${DEVICE_SERIAL}' is enrolled but its model changed: expected '${saved_model}', got '${DEVICE_MODEL}'." + return 2 + fi + + if [[ -n "${saved_fingerprint}" && "${DEVICE_FINGERPRINT}" != "${saved_fingerprint}" ]]; then + _error "Device '${DEVICE_SERIAL}' is enrolled but its build fingerprint changed." + _error " expected: ${saved_fingerprint}" + _error " got: ${DEVICE_FINGERPRINT}" + return 2 + fi + + return 0 +} + +# Fails closed: an unknown device aborts. Any ENROLLED device is accepted, +# so several phones can be managed from one PC without re-enrolling on +# every switch. Only a completely empty store is permissive, and that is +# the first-run case where there is nothing yet to contradict. adb_verify_trusted_identity() { - local saved_model="" - local saved_fingerprint="" - local saved_serial="" + local record="" rc=0 + local -a records=() - if [[ ! -f "${TRUSTED_DEVICE_FILE}" ]]; then - _warn "No trusted device record found. Run 'fresh-phone' to enroll this device." - return 0 - fi + if [[ -d "${TRUSTED_DEVICE_DIR}" ]]; then + for record in "${TRUSTED_DEVICE_DIR}"/*.sh; do + [[ -e "${record}" ]] && records+=("${record}") + done + fi + # Legacy single-device record stays authoritative until it is migrated, + # so an existing install keeps its guarantee without any manual step. + [[ -f "${_PHONE_STATE_DIR}/trusted_device.sh" ]] && + records+=("${_PHONE_STATE_DIR}/trusted_device.sh") - if ! _load_trusted_device_values; then - _fatal "Trusted device record exists but could not be read: ${TRUSTED_DEVICE_FILE}" - fi + if [[ ${#records[@]} -eq 0 ]]; then + _warn "No trusted device record found. Run 'fresh-phone' to enroll this device." + return 0 + fi - saved_serial="${TRUSTED_SERIAL_LOADED:-}" - saved_model="${TRUSTED_MODEL_LOADED:-}" - saved_fingerprint="${TRUSTED_FINGERPRINT_LOADED:-}" - adb_collect_identity + adb_collect_identity - if [[ -n "${saved_serial}" && "${DEVICE_SERIAL}" != "${saved_serial}" ]]; then - _fatal "Device identity mismatch: expected serial '${saved_serial}', got '${DEVICE_SERIAL}'. Refusing to proceed automatically." - fi + for record in "${records[@]}"; do + _matches_trusted_record "${record}" && { + _info "Device identity verified: ${DEVICE_SERIAL} (${DEVICE_MODEL})" + return 0 + } + rc=$? + # A tampered/reflashed match must abort rather than fall through to + # the next record, which would silently downgrade the check. + [[ "${rc}" -eq 2 ]] && _fatal "Refusing to proceed automatically." + done - if [[ -n "${saved_model}" && "${DEVICE_MODEL}" != "${saved_model}" ]]; then - _fatal "Device identity mismatch: expected model '${saved_model}', got '${DEVICE_MODEL}'. Refusing to proceed automatically." - fi - - if [[ -n "${saved_fingerprint}" && "${DEVICE_FINGERPRINT}" != "${saved_fingerprint}" ]]; then - _fatal "Device identity mismatch: expected fingerprint '${saved_fingerprint}', got '${DEVICE_FINGERPRINT}'. Refusing to proceed automatically." - fi - - _info "Device identity verified: ${DEVICE_SERIAL} (${DEVICE_MODEL})" + _error "Device '${DEVICE_SERIAL}' (${DEVICE_MODEL}) is not enrolled." + _error "Enrolled: $(adb_list_trusted_serials | tr '\n' ' ')" + _fatal "Refusing to proceed automatically. Enroll it first if this is expected." } _adb_release_lock() { - if [[ -n "${LOCK_FILE}" && -d "${LOCK_FILE}" ]]; then - rm -rf "${LOCK_FILE}" - fi + if [[ -n "${LOCK_FILE}" && -d "${LOCK_FILE}" ]]; then + rm -rf "${LOCK_FILE}" + fi } adb_acquire_lock() { - local lock_pid_file="" - local old_pid="" + local lock_pid_file="" + local old_pid="" - mkdir -p "${LOCK_DIR}" - LOCK_FILE="${LOCK_DIR}/run_phone.lock" - lock_pid_file="${LOCK_FILE}/pid" + mkdir -p "${LOCK_DIR}" + LOCK_FILE="${LOCK_DIR}/run_phone.lock" + lock_pid_file="${LOCK_FILE}/pid" - if mkdir "${LOCK_FILE}" 2>/dev/null; then - printf '%s\n' "$$" >"${lock_pid_file}" - trap _adb_release_lock EXIT INT TERM - _info "Acquired run lock (PID $$)" - return 0 - fi + if mkdir "${LOCK_FILE}" 2>/dev/null; then + printf '%s\n' "$$" >"${lock_pid_file}" + trap _adb_release_lock EXIT INT TERM + _info "Acquired run lock (PID $$)" + return 0 + fi - old_pid="$(cat "${lock_pid_file}" 2>/dev/null || printf '')" - if [[ -n "${old_pid}" ]] && kill -0 "${old_pid}" 2>/dev/null; then - _fatal "Another run_phone.sh instance is already running (PID ${old_pid}). Aborting." - fi + old_pid="$(cat "${lock_pid_file}" 2>/dev/null || printf '')" + if [[ -n "${old_pid}" ]] && kill -0 "${old_pid}" 2>/dev/null; then + _fatal "Another run_phone.sh instance is already running (PID ${old_pid}). Aborting." + fi - _warn "Stale lock directory found (PID ${old_pid} no longer running). Removing." - rm -rf "${LOCK_FILE}" + _warn "Stale lock directory found (PID ${old_pid} no longer running). Removing." + rm -rf "${LOCK_FILE}" - if ! mkdir "${LOCK_FILE}" 2>/dev/null; then - _fatal "Could not acquire run lock at ${LOCK_FILE}. Another process may have raced us." - fi + if ! mkdir "${LOCK_FILE}" 2>/dev/null; then + _fatal "Could not acquire run lock at ${LOCK_FILE}. Another process may have raced us." + fi - printf '%s\n' "$$" >"${lock_pid_file}" - trap _adb_release_lock EXIT INT TERM - _info "Acquired run lock (PID $$)" + printf '%s\n' "$$" >"${lock_pid_file}" + trap _adb_release_lock EXIT INT TERM + _info "Acquired run lock (PID $$)" } adb_check_cooldown() { - local cooldown_secs="${1:-300}" - local elapsed=0 - local last_run=0 - local marker_name="${2:-default}" - local marker="${LAST_RUN_DIR}/${marker_name}" - local now=0 + local cooldown_secs="${1:-300}" + local elapsed=0 + local last_run=0 + local marker_name="${2:-default}" + local marker="${LAST_RUN_DIR}/${marker_name}" + local now=0 - mkdir -p "${LAST_RUN_DIR}" - if [[ -f "${marker}" ]]; then - last_run="$(cat "${marker}")" - if [[ "${last_run}" =~ ^[0-9]+$ ]]; then - now="$(date +%s)" - elapsed=$((now - last_run)) - if ((elapsed < cooldown_secs)); then - _info "Cooldown active: last run ${elapsed}s ago, cooldown is ${cooldown_secs}s. Skipping." - return 1 - fi - else - _warn "Ignoring invalid cooldown marker: ${marker}" - fi - fi + mkdir -p "${LAST_RUN_DIR}" + if [[ -f "${marker}" ]]; then + last_run="$(cat "${marker}")" + if [[ "${last_run}" =~ ^[0-9]+$ ]]; then + now="$(date +%s)" + elapsed=$((now - last_run)) + if ((elapsed < cooldown_secs)); then + _info "Cooldown active: last run ${elapsed}s ago, cooldown is ${cooldown_secs}s. Skipping." + return 1 + fi + else + _warn "Ignoring invalid cooldown marker: ${marker}" + fi + fi - return 0 + return 0 } adb_mark_last_run() { - local marker_name="${1:-default}" + local marker_name="${1:-default}" - mkdir -p "${LAST_RUN_DIR}" - date +%s >"${LAST_RUN_DIR}/${marker_name}" + mkdir -p "${LAST_RUN_DIR}" + date +%s >"${LAST_RUN_DIR}/${marker_name}" } diff --git a/phone_focus_mode/lib/tests/test_adb_common.sh b/phone_focus_mode/lib/tests/test_adb_common.sh index 8d259ab5..f88cc1cc 100755 --- a/phone_focus_mode/lib/tests/test_adb_common.sh +++ b/phone_focus_mode/lib/tests/test_adb_common.sh @@ -130,8 +130,8 @@ test_save_trusted_device_sanitizes_and_quotes() { export ADB_SERIAL='SERIAL123$() ;' adb_save_trusted_device - [[ -f "${TRUSTED_DEVICE_FILE}" ]] || return 1 - trusted_contents="$(cat "${TRUSTED_DEVICE_FILE}")" + [[ -f "${ADB_ENROLLED_DEVICE_FILE}" ]] || return 1 + trusted_contents="$(cat "${ADB_ENROLLED_DEVICE_FILE}")" # Asserting the sanitiser stripped these metacharacters, so the patterns # must stay literal rather than expand. @@ -146,7 +146,7 @@ test_save_trusted_device_sanitizes_and_quotes() { set -euo pipefail source "$1" printf "%s\n" "${TRUSTED_SERIAL:-}" "${TRUSTED_MODEL:-}" "${TRUSTED_FINGERPRINT:-}" - ' bash "${TRUSTED_DEVICE_FILE}" + ' bash "${ADB_ENROLLED_DEVICE_FILE}" ) [[ "${trusted_values[0]:-}" == 'SERIAL123 ' ]] @@ -166,7 +166,7 @@ test_select_device_rejects_multiple_devices_even_with_trusted_record() { printf 'SERIAL123\nSERIAL999\n' } - cat >"${TRUSTED_DEVICE_FILE}" <<'EOF' + cat >"${ADB_ENROLLED_DEVICE_FILE}" <<'EOF' TRUSTED_SERIAL='SERIAL123' TRUSTED_MODEL='Pixel 7rm -rf /dangerline2' TRUSTED_FINGERPRINT='google/pixel:14/UP1A.231005.007/evilcmd' @@ -190,7 +190,7 @@ test_verify_trusted_identity_rejects_model_mismatch() { export ADB_SERIAL='SERIAL123' adb_save_trusted_device - cat >"${TRUSTED_DEVICE_FILE}" <<'EOF' + cat >"${ADB_ENROLLED_DEVICE_FILE}" <<'EOF' TRUSTED_SERIAL='SERIAL123' TRUSTED_MODEL='Different Model' TRUSTED_FINGERPRINT='google/pixel:14/UP1A.231005.007/evilcmd' @@ -207,7 +207,7 @@ test_verify_trusted_identity_rejects_fingerprint_mismatch() { export ADB_SERIAL='SERIAL123' adb_save_trusted_device - cat >"${TRUSTED_DEVICE_FILE}" <<'EOF' + cat >"${ADB_ENROLLED_DEVICE_FILE}" <<'EOF' TRUSTED_SERIAL='SERIAL123' TRUSTED_MODEL='Pixel 7rm -rf /dangerline2' TRUSTED_FINGERPRINT='different/fingerprint' @@ -220,6 +220,52 @@ EOF return 0 } +test_verify_trusted_identity_accepts_any_enrolled_device() { + # Two phones enrolled from one PC: the second must not evict the first, + # which is the whole reason the store is a directory. + export ADB_SERIAL='SERIAL_ONE' + adb_save_trusted_device + export ADB_SERIAL='SERIAL_TWO' + adb_save_trusted_device + + adb_verify_trusted_identity >/dev/null 2>&1 || return 1 + + export ADB_SERIAL='SERIAL_ONE' + adb_verify_trusted_identity >/dev/null 2>&1 || return 1 + + return 0 +} + +test_verify_trusted_identity_rejects_unenrolled_device() { + export ADB_SERIAL='SERIAL_ONE' + adb_save_trusted_device + + # An unknown serial must still abort, or multi-device support would have + # quietly turned the guard off. + export ADB_SERIAL='SERIAL_STRANGER' + if (adb_verify_trusted_identity >/dev/null 2>&1); then + return 1 + fi + + return 0 +} + +test_forget_trusted_device_removes_only_that_record() { + export ADB_SERIAL='SERIAL_ONE' + adb_save_trusted_device + export ADB_SERIAL='SERIAL_TWO' + adb_save_trusted_device + + adb_forget_trusted_device 'SERIAL_ONE' >/dev/null 2>&1 + + adb_list_trusted_serials | grep -qx 'SERIAL_TWO' || return 1 + if adb_list_trusted_serials | grep -qx 'SERIAL_ONE'; then + return 1 + fi + + return 0 +} + run_test "_box output without crash" test_box_does_not_crash run_test "adb_check_cooldown 0 returns 0 (proceed)" test_check_cooldown_zero_allows run_test "adb_check_cooldown blocks when marker is fresh" test_check_cooldown_blocks_when_marker_fresh @@ -233,6 +279,9 @@ run_test "adb_select_device rejects multiple devices even with trusted record" t run_test "adb_verify_trusted_identity accepts exact saved identity" test_verify_trusted_identity_accepts_exact_match run_test "adb_verify_trusted_identity rejects model mismatch" test_verify_trusted_identity_rejects_model_mismatch run_test "adb_verify_trusted_identity rejects fingerprint mismatch" test_verify_trusted_identity_rejects_fingerprint_mismatch +run_test "adb_verify_trusted_identity accepts any enrolled device" test_verify_trusted_identity_accepts_any_enrolled_device +run_test "adb_verify_trusted_identity rejects unenrolled device" test_verify_trusted_identity_rejects_unenrolled_device +run_test "adb_forget_trusted_device removes only that record" test_forget_trusted_device_removes_only_that_record printf '\nResults: %d passed, %d failed\n' "${PASS}" "${FAIL}" [[ "${FAIL}" -eq 0 ]]