Compare commits

...

3 Commits

Author SHA1 Message Date
553c395cff inFakt is SMS-only 2FA, so the wipe cannot strand the account
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
This was the last blocker on the Device Owner decision. Checked in the
web panel: "Aplikacja weryfikacyjna" is unconfigured, so no TOTP seed
exists for a wipe to destroy, and only "Wrazliwe" actions are gated --
"Logowanie" is unchecked, so plain login needs the password alone. The
registered SMS number lives on the SIM, which survives.

The browser-login approval tap is a Firebase push prompt
(FirebaseInstanceIdReceiver on the device). Push tokens are per-install,
so a reinstall re-registers; and if that ever misbehaved, SMS is still
the fallback.

Corrects the wipe checklist, which assumed TOTP secrets were "likely"
inside the KeePassDX database and treated the .kdbx as a seed backup.
Neither holds: the canonical .kdbx is on the PC, and there are no seeds.
Earlier advice in this session to fetch inFakt backup codes was likewise
for the OTP-app variant this account does not use.

What still does not survive is unchanged and unrelated to 2FA: the
banking pairing ("Usun powiazanie z telefonem") and the local app PIN,
re-paired via SMS like mBank.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JxNrcMDcizNB3XrrYpZF23
2026-08-10 20:04:06 +02:00
7b1a1656f7 Back up what adb can actually reach, and block YouTube in Firefox too
phone_backup.sh captures package lists (including what was purged for
user 0), every third-party APK with its splits, /sdcard, all three
settings namespaces, and the focus-mode state. Verified: 54/54 packages,
126 APK files, 5.1 GB, splits intact.

It is deliberately not sold as a full-device backup, because on an
unrooted phone it cannot be one: /data/data is unreachable, so logins,
in-app data and device pairings do not survive. It writes a
RESTORE-BY-HAND.md naming each of those, with a restore order that avoids
a lockout -- mObywatel last, because activating it on a new device
deactivates the old one.

The first two runs pulled 1 of 54 APKs and then 6 of 54: `while read <
file` with adb inside the loop lets adb drain the same stdin. Reading
into an array first fixes it, and verify_backup now compares package
count against the manifest rather than only checking that the files it
did pull are valid zips -- integrity alone called the 1-of-54 run a pass.

Also documents the uBlock Origin filters, which block YouTube in Firefox
independently of RethinkDNS: force-stopping the VPN still leaves
youtube.com blocked by ||youtube.com^. And records what this is worth --
Play offers a one-tap Install for YouTube, the VPN is a few taps from
off, and the uBlock page has a Proceed button. Three independent layers,
none of them tamper-proof; only Device Owner removes the off switch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JxNrcMDcizNB3XrrYpZF23
2026-08-10 19:43:28 +02:00
10fff1d1a8 Block YouTube on the unrooted Pixel, and trust more than one phone
`pm uninstall --user 0` unregisters a package for one user while leaving
the APK on the system image. It needs no root 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 one. Applied to the YouTube
app, YouTube Music, and Chrome; `--restore` puts any of them back with no
download.

focus_owner could not have done this: 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.

Verified on 23181JEGR08034 across two reboots: all three read
installed=false, and in Firefox m.youtube.com, www.youtube.com, a /watch
URL and a youtu.be short link all fail to connect while example.com
loads. The web half of that is RethinkDNS domain rules, which live on the
device and are not in this commit; docs/youtube-block-unrooted.md records
how to rebuild them, and what this does NOT resist -- the VPN is a few
taps from off, which only Device Owner can prevent.

The trusted-device record becomes one file per device, so managing a
second phone no longer evicts the first. Unenrolled devices still abort,
and a changed model or build fingerprint aborts rather than falling
through to the next record.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JxNrcMDcizNB3XrrYpZF23
2026-08-10 19:16:01 +02:00
9 changed files with 1115 additions and 168 deletions

View File

@ -46,9 +46,19 @@ Present and relevant:
| mObywatel | `pl.nask.mobywatel` | No — full re-activation |
**No dedicated TOTP app is installed**, so the usual "authenticator seeds are
destroyed by the wipe" trap does not apply — unless your TOTP secrets live
inside the KeePassDX database, which is likely. If so, the `.kdbx` file _is_
your seed backup, and step 2 covers it.
destroyed by the wipe" trap does not apply.
Checked 2026-08-09, and it does not apply via KeePassDX either: the `.kdbx`
lives in KeePassDX's private storage (not on `/sdcard`, so `phone_backup.sh`
cannot reach it), but the canonical copy is on the PC. And **inFakt — the one
account whose loss would have blocked this wipe — is SMS-only 2FA**:
"Aplikacja weryfikacyjna" is unconfigured, so no seed exists to lose, and
_Logowanie_ is not among the 2FA-gated actions. See
`phone_focus_mode/docs/youtube-block-unrooted.md`.
`pl.infakt.infakt` belongs in the table above: the account is server-side and
survives, but its **banking pairing does not** — re-pair via SMS, same as
mBank.
## Phase A — break the circular dependency first

View File

@ -0,0 +1,39 @@
{
"intent": "Settle whether a Device Owner factory reset would lock the user out of inFakt, which was the last blocker on that decision.",
"scope": [
"phone_focus_mode/docs/youtube-block-unrooted.md",
"docs/device-owner-wipe-checklist.md",
"Documentation only -- no code, no device state changed"
],
"changes": [
"Recorded that inFakt 2FA is SMS-only and that no TOTP seed exists, so a wipe cannot destroy one.",
"Corrected the wipe checklist, which assumed TOTP secrets were 'likely' inside the KeePassDX database and treated the .kdbx as a seed backup. Neither holds: the user keeps the canonical .kdbx on the PC, and inFakt has no authenticator configured.",
"Added pl.infakt.infakt to the set of apps whose banking pairing does not survive the wipe."
],
"verification": [
{
"command": "inFakt web panel, Weryfikacja dwuetapowa (screenshot supplied by the user)",
"result": "pass",
"evidence": "2FA = Wlaczona with SMS to the registered number. 'Aplikacja weryfikacyjna' shows a 'Skonfiguruj' link, i.e. NOT configured -- no TOTP seed. Under 'Akcje objete weryfikacja dwuetapowa' only 'Wrazliwe' is checked; 'Logowanie' and 'Wystawianie faktur' are unchecked, so plain login needs the password alone."
},
{
"command": "adb shell dumpsys package pl.infakt.infakt | grep -i c2dm/firebase",
"result": "pass",
"evidence": "FirebaseInstanceIdReceiver registered for com.google.android.c2dm.intent.RECEIVE, so the browser-login approval tap is a push prompt. Push tokens are per-install, so a reinstall re-registers rather than stranding the account."
},
{
"command": "adb shell dumpsys account | grep -i infakt",
"result": "pass",
"evidence": "No device account entry -- nothing stored locally that a wipe would destroy beyond the pairing and app PIN."
}
],
"risks": [
"The push-reinstall behaviour is inferred from the Firebase receiver plus vendor docs, not from a stated 'reinstalling does not lock you out'. It is safe to act on because the second factor is SMS and the SIM survives -- if push re-registration misbehaved, SMS still works.",
"Earlier in this session the user was advised to download inFakt backup codes. That advice applies to the extended OTP-app variant, which this account does not use; with SMS-only 2FA the recovery path is the SIM. Corrected rather than left standing.",
"The 2FA settings page warns that saving changes logs out all current mobile sessions, so it should not be edited casually.",
"Still unresolved and unchanged: inFakt's banking side is device-paired and holds a live session with funds and an active card. Re-pairing after a wipe goes through SMS."
],
"rollback": [
"git revert -- documentation only, nothing on the device depends on it."
]
}

View File

@ -0,0 +1,48 @@
{
"intent": "Add a second, VPN-independent YouTube block in Firefox, and give the phone a backup script covering everything ADB can actually reach before a possible Device Owner factory reset.",
"scope": [
"phone_focus_mode/phone_backup.sh",
"phone_focus_mode/docs/youtube-block-unrooted.md",
"Non-goal: app private data -- unreachable without root, documented rather than faked",
"Non-goal: tamper-resistance; only Device Owner removes the off switch"
],
"changes": [
"phone_backup.sh captures package lists (including what was purged for user 0), every third-party APK with its splits, /sdcard user data, all three settings namespaces, and the focus-mode state. It ships a RESTORE-BY-HAND.md naming what it cannot restore, and --verify re-reads the artefacts.",
"Documented the uBlock Origin layer: the 8 filters, the import procedure, and why `adb shell input text` must not be used to enter them.",
"Documented measured undo costs for all three layers, including the Play Store finding, so the doc does not overstate the block."
],
"verification": [
{
"command": "./phone_backup.sh --out ~/phone-backup",
"result": "pass",
"evidence": "54/54 packages, 126 APK files, 5.1 GB, 'Verify OK'. Split APKs captured in full (com.termux has base + 5 split_config). Spot-checked 3 random APKs with unzip -t: all OK. pl.infakt.infakt, pl.mbank, com.kunzisoft.keepass.libre and org.thoughtcrime.securesms all present."
},
{
"command": "force-stop com.celzero.bravedns, then load youtube.com in Firefox",
"result": "pass",
"evidence": "'uBlock Origin has prevented the following page from loading: https://m.youtube.com/ ... filter ||youtube.com^ ... found in: My filters'. The layers are independent: killing the VPN does not restore YouTube. Control example.com still loads; VPN restored afterwards."
},
{
"command": "market://details?id=com.google.android.youtube",
"result": "fail",
"evidence": "Google Play shows a live Install button, so the app-removal layer is a ONE-TAP undo -- weaker than the VPN toggle. Not installed; state re-confirmed installed=false. Recorded in the doc rather than left implicit."
},
{
"command": "shellcheck + shfmt on phone_backup.sh",
"result": "pass",
"evidence": "Clean."
}
],
"risks": [
"The first two runs of phone_backup.sh pulled 1 of 54 and then 6 of 54 APKs. Cause: `while read < file` with `adb` inside the loop -- adb inherits and drains the same stdin. Fixed by reading into an array with mapfile first; the same bug was fixed in the .kdbx loop. verify_backup now compares package-directory count against packages-third-party.txt, because an integrity-only check called the 1-of-54 run a pass.",
"Backgrounding the script with nohup truncated it mid-run twice; it must be run in the foreground. Not a script defect but worth knowing before trusting an unattended run.",
"No .kdbx is captured: KeePassDX keeps its database in private storage. Confirmed with the user that the canonical copy lives on the PC, so this is expected here -- downgraded from a warning to an info line, which means a genuinely missing database on some other device would be quieter.",
"infakt (pl.infakt.infakt) is device-paired for banking ('Usun powiazanie z telefonem') and holds a live session with funds and an active card. The account is server-side so login works on a new device, but the pairing and app PIN do not survive a wipe; re-pairing is via SMS to the number registered in-app. 2FA method (SMS vs authenticator) still unconfirmed by the user.",
"uBlock filters live in the Firefox profile and are NOT in the backup; they must be re-added by hand after a wipe."
],
"rollback": [
"git revert removes the script and doc changes; no device state is touched by reverting.",
"Delete a backup directory under ~/phone-backup/ to reclaim space -- each full run is ~5 GB.",
"Remove the uBlock filters from uBlock dashboard -> My filters and press apply."
]
}

View File

@ -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 <pkg>; 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."
]
}

View File

@ -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 <pkg>` 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 "$@"

View File

@ -0,0 +1,166 @@
# 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 <pkg>`: 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.
## Layer 2: uBlock Origin in Firefox
Independent of the VPN, and that is the point: stopping RethinkDNS does
**not** restore YouTube in Firefox. Verified by force-stopping
`com.celzero.bravedns` and loading youtube.com, which produced _"uBlock
Origin has prevented the following page from loading — `||youtube.com^` —
found in: My filters"_.
The filters, in uBlock's dashboard → **My filters**:
```
! YouTube block
||youtube.com^
||youtu.be^
||googlevideo.com^
||ytimg.com^
||youtube-nocookie.com^
||ggpht.com^
||yt3.ggpht.com^
||m.youtube.com^
```
Add them by writing that list to a file, pushing it to
`/sdcard/Download/`, triggering a media scan (`am broadcast -a
android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:///sdcard/...`,
or the picker will not see it), then using uBlock's **import** button.
Do NOT type them with `adb shell input text`: it silently strips `|` and
`^`, leaving bare domains that do not block. Press the checkmark to
apply, and confirm it greys out.
These live in the Firefox profile, so they are **not** captured by
`phone_backup.sh` and must be re-added by hand after a wipe.
The block page has a **Proceed** button — one tap. This layer raises the
cost of bypassing; it does not remove the bypass.
## 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.
## How strong this actually is
Measured, not assumed:
| Layer | Undo cost |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| App removal | **One tap.** Google Play shows a live **Install** button for YouTube (checked on device 2026-08-09; not installed). |
| RethinkDNS rules | A few taps — the VPN toggle in Settings or the quick-settings tile. |
| uBlock filters | **Proceed** on the block page, or disabling the extension. |
Nothing here is tamper-resistant, and nothing here can be: on an
unrooted device without Device Owner, no app can prevent the user
disabling a VPN or reinstalling from Play. The layers are independent —
undoing one does not undo the others — so the cost is "three separate
places" rather than one. That is the honest ceiling.
`DISALLOW_CONFIG_VPN` plus `setAlwaysOnVpnPackage(..., lockdown)` under
Device Owner is the only tier that removes the off switch, and it needs
the factory reset in `docs/device-owner-wipe-checklist.md`. See also the
FLAG_SYSTEM note above: `focus_owner` would need fixing before Device
Owner could touch YouTube at all.
Also note nothing re-asserts the purge automatically.
`phone-auto-sync.timer` is inactive and its `ExecStart` points at a path
that does not exist, so `distraction_purge.sh` is manual today.
## infakt, before any factory reset
Checked 2026-08-09 in the web panel and on the device, because infakt was
the one app whose loss would have blocked the Device Owner wipe.
- **2FA is SMS-only.** "Aplikacja weryfikacyjna" reads _Skonfiguruj_, i.e.
not configured, so **no TOTP seed exists** and a wipe cannot destroy
one. The registered number survives on the SIM.
- **"Logowanie" is unchecked** under _Akcje objęte weryfikacją_ — only
_Wrażliwe_ actions prompt. Plain login needs the password alone.
- The app uses Firebase push (`FirebaseInstanceIdReceiver`) for the
browser-login approval tap. Push tokens are per-install, so a reinstall
re-registers and prompts arrive at the new install.
So login is safe: reinstall, sign in with the password.
What does **not** survive: the banking pairing (_Usuń powiązanie z
telefonem_) and the local app PIN. Re-pair via SMS after the wipe.
Do not save anything on that settings page casually — it warns that
changing it logs out all current mobile sessions.
## 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.

View File

@ -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}"
}

View File

@ -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 ]]

333
phone_focus_mode/phone_backup.sh Executable file
View File

@ -0,0 +1,333 @@
#!/usr/bin/env bash
# ============================================================
# Phone backup — everything ADB can reach on an UNROOTED device
#
# READ THIS FIRST. This is NOT a full-device backup and cannot
# be one. Restoring from it does NOT give you the phone back as
# it was; it gives you your FILES back and a checklist of what
# to reinstall and re-authenticate by hand.
#
# What it captures:
# - every installed package name, split into system/third-party
# - the APK of every third-party app (so you can reinstall
# offline, including F-Droid apps that may have moved on)
# - /sdcard user data: DCIM, Pictures, Download, Documents,
# Movies, Music, plus Signal backups if present
# - settings (system/secure/global), which covers most of the
# phone's own configuration
# - the focus-mode state: which packages are purged, and the
# RethinkDNS domain rules if its export is present
#
# What it CANNOT capture, on any unrooted phone:
# - app private data (/data/data/<pkg>): logins, sessions,
# in-app settings, message history, game saves
# - anything hardware-bound: bank device pairings, infakt's
# phone pairing, mObywatel activation, Signal registration
# - the Firefox profile (tabs, cookies, extension settings)
#
# Reading another app's private storage needs root or a
# debuggable build. `adb backup` is deprecated and a no-op for
# most apps since Android 12. That is a platform limit, not a
# gap in this script -- so it prints, at the end, an explicit
# list of what you will have to redo by hand.
#
# Usage:
# ./phone_backup.sh [--out DIR] [--no-apks] [--verify DIR]
# ============================================================
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"
OUT_ROOT="${HOME}/phone-backup"
PULL_APKS=1
VERIFY_DIR=""
# Directories pulled wholesale from shared storage. Anything not
# listed here is not backed up, so keep the list honest.
readonly SDCARD_DIRS=(
DCIM
Pictures
Download
Documents
Movies
Music
Signal
RunnerUp
)
usage() {
sed -n '2,36p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
exit 0
}
while [[ $# -gt 0 ]]; do
case "$1" in
--out)
OUT_ROOT="${2:?--out needs a directory}"
shift 2
;;
--no-apks)
PULL_APKS=0
shift
;;
--verify)
VERIFY_DIR="${2:?--verify needs a directory}"
shift 2
;;
-h | --help) usage ;;
*)
_error "Unknown flag: $1"
exit 1
;;
esac
done
# A backup nobody checked is not a backup. --verify re-reads the
# artefacts and fails loudly on anything empty or missing.
verify_backup() {
local dir="${1:?}" failed=0 f=""
_info "Verifying ${dir}"
for f in packages-all.txt packages-third-party.txt settings-secure.txt manifest.txt; do
if [[ ! -s "${dir}/${f}" ]]; then
_error "missing or empty: ${f}"
failed=1
fi
done
if [[ -d "${dir}/apks" ]]; then
local apk_count=0 broken=0 pkg_dirs=0 expected=0
while IFS= read -r -d '' apk; do
apk_count=$((apk_count + 1))
# An APK is a zip; a truncated pull is the failure mode.
unzip -t "${apk}" >/dev/null 2>&1 || {
_error "corrupt APK: $(basename "${apk}")"
broken=1
}
done < <(find "${dir}/apks" -name '*.apk' -print0 2>/dev/null)
# Coverage, not just integrity: the stdin bug produced ONE
# perfectly valid APK out of 54, which an integrity-only check
# would have called a pass.
pkg_dirs="$(find "${dir}/apks" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)"
expected="$(wc -l <"${dir}/packages-third-party.txt")"
_info "APKs: ${apk_count} files across ${pkg_dirs}/${expected} packages"
if [[ "${pkg_dirs}" -lt "${expected}" ]]; then
_error "only ${pkg_dirs} of ${expected} packages have APKs"
failed=1
fi
[[ "${broken}" -eq 1 ]] && failed=1
fi
local kdbx_count=0
kdbx_count="$(find "${dir}/sdcard" -iname '*.kdbx' 2>/dev/null | wc -l)"
if [[ "${kdbx_count}" -eq 0 ]]; then
# Expected on this phone: the database lives in KeePassDX's
# private storage and the canonical copy is on the PC. Noted
# rather than warned so a real regression stays visible.
_info "No .kdbx in shared storage (canonical copy is on the PC)"
else
_info "KeePassDX databases: ${kdbx_count}"
fi
if [[ "${failed}" -eq 1 ]]; then
_error "VERIFY FAILED"
return 1
fi
_info "Verify OK"
}
dump_packages() {
local dir="$1"
adb_cmd shell pm list packages | sed 's/^package://' | tr -d '\r' |
sort >"${dir}/packages-all.txt"
adb_cmd shell pm list packages -3 | sed 's/^package://' | tr -d '\r' |
sort >"${dir}/packages-third-party.txt"
# Packages removed for user 0 read as uninstalled here; recorded
# separately so a restore knows what was deliberately purged.
adb_cmd shell pm list packages -u | sed 's/^package://' | tr -d '\r' |
sort >"${dir}/packages-including-removed.txt"
comm -13 "${dir}/packages-all.txt" "${dir}/packages-including-removed.txt" \
>"${dir}/packages-removed-for-user0.txt"
_info "Packages: $(wc -l <"${dir}/packages-third-party.txt") third-party, $(wc -l <"${dir}/packages-removed-for-user0.txt") removed for user 0"
}
pull_apks() {
local dir="$1" pkg="" path="" n=0 base=""
local -a pkgs=() paths=()
mkdir -p "${dir}/apks"
# Read the list into an array FIRST. Iterating the file with
# `while read < file` breaks after one package, because `adb`
# inside the loop inherits and drains that same stdin -- measured:
# it pulled 1 of 54 before this was fixed.
mapfile -t pkgs <"${dir}/packages-third-party.txt"
for pkg in "${pkgs[@]}"; do
[[ -n "${pkg}" ]] || continue
# A split app reports several paths (base + split_config.*).
# All of them are needed for a working offline reinstall, so
# each package gets its own directory rather than one file.
mapfile -t paths < <(
adb_cmd shell pm path "${pkg}" 2>/dev/null |
sed 's/^package://' | tr -d '\r'
)
[[ "${#paths[@]}" -gt 0 ]] || {
_warn "no APK path for ${pkg}"
continue
}
mkdir -p "${dir}/apks/${pkg}"
for path in "${paths[@]}"; do
[[ -n "${path}" ]] || continue
base="$(basename "${path}")"
adb_cmd pull "${path}" "${dir}/apks/${pkg}/${base}" >/dev/null 2>&1 ||
_warn "could not pull ${base} for ${pkg}"
done
n=$((n + 1))
done
_info "APKs pulled: ${n} packages, $(find "${dir}/apks" -name '*.apk' | wc -l) files"
}
pull_sdcard() {
local dir="$1" d=""
mkdir -p "${dir}/sdcard"
for d in "${SDCARD_DIRS[@]}"; do
if adb_cmd shell "test -d /sdcard/${d}" 2>/dev/null; then
_info "Pulling /sdcard/${d}"
adb_cmd pull "/sdcard/${d}" "${dir}/sdcard/" >/dev/null 2>&1 ||
_warn "partial or failed pull: ${d}"
fi
done
# Same stdin caveat as pull_apks: collect first, pull second.
local -a kdbx_paths=()
mapfile -t kdbx_paths < <(
adb_cmd shell 'find /sdcard -iname "*.kdbx" 2>/dev/null' | tr -d '\r'
)
local kdbx=""
for kdbx in "${kdbx_paths[@]}"; do
[[ -n "${kdbx}" ]] || continue
_info "Pulling KeePass database: ${kdbx}"
mkdir -p "${dir}/sdcard/keepass"
adb_cmd pull "${kdbx}" "${dir}/sdcard/keepass/" >/dev/null 2>&1 || true
done
}
dump_settings() {
local dir="$1" ns=""
for ns in system secure global; do
adb_cmd shell settings list "${ns}" | tr -d '\r' | sort \
>"${dir}/settings-${ns}.txt"
done
_info "Settings captured (system/secure/global)"
}
dump_focus_state() {
local dir="$1"
{
printf '# Focus-mode state at backup time\n'
printf '# Restore with: phone_focus_mode/distraction_purge.sh\n\n'
printf '## Packages removed for user 0\n'
cat "${dir}/packages-removed-for-user0.txt"
printf '\n## RethinkDNS installed: '
grep -qx 'com.celzero.bravedns' "${dir}/packages-all.txt" &&
printf 'yes\n' || printf 'no\n'
printf '## uBlock filters live in the Firefox profile and CANNOT be\n'
printf '## backed up from adb; see docs/youtube-block-unrooted.md\n'
} >"${dir}/focus-state.md"
}
write_manifest() {
local dir="$1"
{
printf 'Backup of %s (%s)\n' "${DEVICE_SERIAL}" "${DEVICE_MODEL}"
printf 'Fingerprint: %s\n' "${DEVICE_FINGERPRINT}"
printf 'Taken: %s\n' "$(date -Is)"
printf 'Android: %s (SDK %s)\n' \
"$(adb_cmd shell getprop ro.build.version.release | tr -d '\r')" \
"$(adb_cmd shell getprop ro.build.version.sdk | tr -d '\r')"
printf '\nContents:\n'
du -sh "${dir}"/* 2>/dev/null | sed 's/^/ /'
} >"${dir}/manifest.txt"
}
print_manual_checklist() {
local dir="$1"
cat >"${dir}/RESTORE-BY-HAND.md" <<'EOF'
# What this backup does NOT restore
Everything below is app-private or hardware-bound, so it is unreachable
from adb on an unrooted phone. Budget real time for it after a wipe.
## Must be re-authenticated (device pairing / re-activation)
- **infakt** (`pl.infakt.infakt`) — the account itself is server-side, so
login + password works on a new device. BUT its banking side is
device-paired ("Usuń powiązanie z telefonem" in Ustawienia bankowości)
and the app PIN is local. Expect to re-pair via SMS to the registered
number. Confirm 2FA method BEFORE wiping: SMS is safe, an authenticator
app means the seed must be in KeePassDX.
- **mBank** (`pl.mbank`) — re-pair the device, SMS code, new app PIN.
- **Revolut** — re-login, SMS/email, possibly selfie re-verification.
- **mObywatel** (`pl.nask.mobywatel`) — full re-activation via Profil
Zaufany or a bank login. Do this LAST: activating on a new device
deactivates the old one, with no rollback.
- **Signal** — needs its own backup + the 30-digit passphrase. The
restore prompt appears at install time ONLY.
## Lost unless separately exported
- Firefox: tabs, cookies, logins, and the uBlock Origin filter list
- App settings and in-app data for every third-party app
- Game/app progress not synced to a server
## Restore order that avoids a lockout
1. Google account (needs backup codes if 2FA is on a device you wiped)
2. KeePassDX, from the `.kdbx` in `sdcard/keepass/`
3. Signal, at install time
4. Banks (mBank, Revolut, infakt)
5. mObywatel last
6. Re-apply focus mode: `distraction_purge.sh`, reinstall RethinkDNS and
re-add its domain rules, re-add the uBlock filters
EOF
_info "Wrote ${dir}/RESTORE-BY-HAND.md -- read it before relying on this backup"
}
main() {
if [[ -n "${VERIFY_DIR}" ]]; then
verify_backup "${VERIFY_DIR}"
return
fi
adb_select_device
adb_verify_trusted_identity
local stamp="" dir=""
stamp="$(date +%Y-%m-%d-%H%M%S)"
dir="${OUT_ROOT}/${DEVICE_SERIAL}-${stamp}"
mkdir -p "${dir}"
_box "PHONE BACKUP" \
"Device: ${DEVICE_MODEL} (${DEVICE_SERIAL})" \
"Output: ${dir}" \
"This does NOT capture app private data -- see RESTORE-BY-HAND.md"
dump_packages "${dir}"
[[ "${PULL_APKS}" -eq 1 ]] && pull_apks "${dir}"
pull_sdcard "${dir}"
dump_settings "${dir}"
dump_focus_state "${dir}"
print_manual_checklist "${dir}"
write_manifest "${dir}"
verify_backup "${dir}"
_info "Backup complete: ${dir}"
_info "Total size: $(du -sh "${dir}" | cut -f1)"
}
main "$@"