Compare commits

..

No commits in common. "d0fcda3a4715af353d01857b55b0104066a3369f" and "7cfe188bbe212b860c3bbab9ce68a8c212999e22" have entirely different histories.

14 changed files with 0 additions and 1236 deletions

View File

@ -1,24 +0,0 @@
{
"title": "Prove DPM app-hiding persists, and build the enforcement decision layer on it",
"objective": "The Device Owner design rests on setApplicationHidden surviving a reboot, which had never been tested - both shell primitives were measured to be cleared by one. Prove or disprove that WITHOUT spending a factory reset, then build the decision layer that turns the parsed policy plus current conditions into a hide/show set. Success is a measured persistence result with its scope stated honestly, and a pure, fully tested decision function.",
"acceptance_criteria": [
"setApplicationHidden persistence measured across a real reboot, using a removable managed profile so no wipe is spent",
"The test profile and its profile-owner grant are removed afterwards, with user 0 verified untouched",
"The result is recorded with its scope limit: profile owner in a work profile is NOT device owner in user 0",
"EnforcementDecision is a pure function of its inputs - testable with no device, clock or location provider",
"packagesToShow is always the complete allowed set rather than a delta, so a missed run self-repairs",
"Unknown location enforces rather than releasing, matching focus_daemon.sh",
"A policy with redacted coordinates still enforces rather than reading as always-away",
"Geofence hysteresis prevents flapping between radius and radius+hysteresis",
"The workout exception releases the YouTube packages and nothing else",
"Workout signal sources are verified on-device before being built, not assumed"
],
"out_of_scope": [
"Device Owner provisioning and the factory reset - unchanged, still not done",
"The foreground service, BOOT_COMPLETED receiver and alarm scheduling - next step",
"DNS filtering, which remains parked",
"com.kuhy.workout_app as a signal source: verified to expose nothing readable",
"org.runnerup: not installed on this device"
],
"verifier": "pm create-user/dpm set-profile-owner + adb reboot + dumpsys package, then pm remove-user and re-check user 0; cd focus_owner && flutter analyze && flutter test"
}

View File

@ -1,22 +0,0 @@
{
"title": "Home coordinates out of git, layered workout detection, and removal of the test hook",
"objective": "Give the geofence its anchor without recording where the user lives in the repository, and replace the root-only workout detector with sources an unrooted app can actually read. Success is coordinates living only in app-private storage, a workout signal that fails closed on every path, and the temporary test receiver gone before it can reach a provisioned build.",
"acceptance_criteria": [
"Home coordinates are pushed from the untracked config_secrets.sh to app-private storage; nothing coordinate-shaped enters git",
"The shipped REDACTED_* placeholder is rejected with a message naming the file to fill in, not written as a nonsense coordinate",
"The provisioned file is mode 600 and unreadable by the shell user",
"The staging copy under /data/local/tmp is removed after the transfer",
"A missing, malformed, or out-of-range coordinate file reads as null rather than throwing, so the enforcement layer treats it as location-unknown and fails closed",
"Every workout source fails closed: a throwing or hanging probe reports no workout",
"The manual signal is time-boxed rather than a plain toggle",
"The combined signal can name which source opened the exception",
"HideTestReceiver is absent from the source, the manifest, and the installed APK"
],
"out_of_scope": [
"Device Owner provisioning and the factory reset",
"The Health Connect query implementation - the guarded wrapper exists, the platform call does not yet",
"The foreground service, BOOT_COMPLETED receiver and alarm scheduling",
"com.kuhy.workout_app and org.runnerup as sources: verified unusable and absent respectively"
],
"verifier": "focus_owner/scripts/push_home_location.sh (both the placeholder-rejection and success paths) then --check; adb run-as ls -la to confirm mode 600; adb shell cat to confirm the shell cannot read it; cd focus_owner && flutter analyze && flutter test; rebuild, reinstall, and dumpsys package | grep -c HideTest"
}

View File

@ -1,51 +0,0 @@
{
"intent": "Settle whether DPM app-hiding survives a reboot without spending a factory reset on the question, then build the enforcement decision layer on the answer.",
"scope": [
"focus_owner/lib/enforcement.dart - new: pure hide/show decision function",
"focus_owner/lib/policy.dart - workoutExemptPackages, mapping unblock domains to packages",
"focus_owner/android/.../DevicePolicyBridge.kt - setApplicationHidden / isApplicationHidden / isProfileOwner",
"focus_owner/android/.../HideTestReceiver.kt - new, TEMPORARY: adb-driveable test hook",
"focus_owner/test/enforcement_test.dart - new: 16 tests",
"Non-goal: no Device Owner provisioning, no factory reset",
"Non-goal: the foreground service, boot receiver and alarms are the next step"
],
"changes": [
"Measured setApplicationHidden persistence using a removable managed profile (pm create-user --profileOf 0 --managed, dpm set-profile-owner) rather than a factory reset. hidden=true before reboot, hidden=true after, confirmed by both dumpsys and the DPM API. The profile was then removed, taking the profile-owner grant and all hidden state with it.",
"EnforcementDecision.evaluate is a pure function of policy plus conditions, so the whole decision layer is testable with no device, clock or location provider.",
"packagesToShow is always the complete allowed set rather than a delta. Unhiding is the failure mode that matters: failing to hide is a mild disappointment, failing to unhide strands the user without a dialer or a bank after a reboot during curfew. Applying the full set every run makes a missed evaluation self-repairing.",
"The workout exception is expressed as packages, not domains. The rooted system unblocked youtube.com in a hosts file; hiding apps cannot target a domain, so workoutExemptPackages derives the package set from the configured domains and keeps config.sh as the source of truth for intent."
],
"verification": [
{
"command": "pm create-user --profileOf 0 --managed; dpm set-profile-owner; am broadcast HIDE; adb reboot; dumpsys package",
"result": "pass",
"evidence": "hidden=true before reboot and hidden=true after, corroborated by the DPM API's own isApplicationHidden ('RESULT query com.android.chrome -> hidden=true'). This is the assumption the entire Device Owner design rests on, and it holds."
},
{
"command": "pm remove-user 10; dumpsys device_policy; dumpsys package com.android.chrome",
"result": "pass",
"evidence": "'Success: removed user'. Device Owner Type: -1, effective restrictions none, and Chrome in user 0 shows hidden=false - the real user was never touched."
},
{
"command": "cd focus_owner && flutter analyze && flutter test",
"result": "pass",
"evidence": "'No issues found!' and 43 tests passing, 16 of them new: away/at-home/curfew transitions, midnight wrap, hysteresis at 160m in both directions, fail-closed on unknown location, fail-closed on redacted coordinates, the workout exception, and an invariant that hide and show partition the installed set."
},
{
"command": "adb shell pm list packages / dumpsys package (workout signal sources)",
"result": "pass",
"evidence": "StrongLifts declares AND is granted android.permission.health.WRITE_EXERCISE, and com.google.android.apps.healthdata is installed, so the Health Connect path is viable. com.kuhy.workout_app exposes only MainActivity plus Flutter boilerplate - no provider or broadcast to read. org.runnerup is not installed at all. Two of the three proposed sources were checked before being built rather than after."
}
],
"risks": [
"SCOPE LIMIT, stated deliberately: persistence was proven for PROFILE OWNER inside a work profile. That is NOT the same as DEVICE OWNER hiding apps in user 0, which is what the real design needs. DO in user 0 additionally cannot hide the current launcher, the default dialer/SMS/IME, or packages the system deems critical, and setApplicationHidden may return false silently rather than throwing. Test this in the first minute after provisioning, while clearDeviceOwnerApp() is still a cheap exit.",
"HideTestReceiver is exported=true. It is gated behind MANAGE_DEVICE_ADMINS, a signature|privileged permission no third-party app can hold, but it is a receiver that applies policy and it must be deleted before any provisioned build. Tracked.",
"BOOT_COMPLETED does not fire until first unlock. Observed directly: the phone sat at RUNNING_LOCKED for several minutes after a reboot with no network and no app start. Enforcement state therefore persists unchanged across a reboot until the user unlocks - fail-closed for hiding, but also fail-closed for unhiding. The service layer must make boundary transitions alarm-driven and idempotent.",
"workoutExemptPackages hardcodes the youtube.com to package mapping. Adding a new unblock domain to config.sh will not automatically map to a package."
],
"rollback": [
"git revert. enforcement.dart is new and nothing outside focus_owner imports it; the app applies no policy in this build.",
"Nothing on the phone needs undoing - the test profile is already removed and user 0 was verified unchanged.",
"After rollback validate: flutter analyze && flutter test still pass, and dumpsys device_policy still reports Device Owner Type: -1."
]
}

View File

@ -1,58 +0,0 @@
{
"intent": "Let the geofence work without committing the user's home coordinates, and detect workouts through channels an unrooted app can read.",
"scope": [
"focus_owner/lib/home_location.dart - new: read/write/clear app-private coordinates",
"focus_owner/scripts/push_home_location.sh - new: provisioning from config_secrets.sh",
"focus_owner/lib/workout_signal.dart - new: manual, guarded and combined sources",
"focus_owner/test/{home_location,workout_signal}_test.dart - new: 24 tests",
"focus_owner/android/.../HideTestReceiver.kt - DELETED, plus its manifest entry",
"Non-goal: no Device Owner provisioning; the app still applies no policy"
],
"changes": [
"Coordinates are pushed to app-private storage rather than committed. The asset stays redacted, and the provisioning script greps config_secrets.sh instead of sourcing it - that file holds other secrets and this script has no business evaluating them.",
"Private storage was chosen for its lifetime as much as its permissions: it does not survive an uninstall, so reinstalling forces re-provisioning rather than silently inheriting a stale home.",
"Every failure mode in HomeLocationStore.read returns null instead of throwing. Null flows into the enforcement layer as location-unknown, which already fails closed into enforcing - so a corrupt file cannot become an unlock, and cannot crash the service either.",
"The manual workout signal is time-boxed rather than a toggle: a workout mode left on by accident is indistinguishable from having no exception at all.",
"GuardedWorkoutSignal catches broadly and times out, because nothing about a workout probe failing should be able to stop enforcement running. CombinedWorkoutSignal can name the source that opened the exception, so the UI can explain an unlock rather than presenting it as magic.",
"HideTestReceiver deleted. It had served its purpose - proving setApplicationHidden persistence - and it applied policy from an exported receiver, which has no place in a build that will later hold device owner."
],
"verification": [
{
"command": "./focus_owner/scripts/push_home_location.sh (real config_secrets.sh)",
"result": "pass",
"evidence": "Exits non-zero with \"HOME_LAT is 'REDACTED_LAT', not a coordinate - fill in .../config_secrets.sh\". The shipped placeholder cannot silently become a geofence anchor."
},
{
"command": "./focus_owner/scripts/push_home_location.sh --secrets <real-shaped> && --check",
"result": "pass",
"evidence": "'Coordinates written to com.kuhy.focus_owner private storage' then 'OK coordinates provisioned (43 bytes)'. --check reports presence and size only, never the coordinates themselves, since its output lands in scrollback and transcripts."
},
{
"command": "adb shell run-as ... ls -la; adb shell cat /data/data/.../home_location.json",
"result": "pass",
"evidence": "-rw------- after an explicit chmod 600 (the default umask had left it 666), and the shell user gets 'Permission denied'. The /data/local/tmp staging copy is gone."
},
{
"command": "cd focus_owner && flutter analyze && flutter test",
"result": "pass",
"evidence": "'No issues found!' and 67 tests passing, 24 new. Covers malformed JSON, a non-object document, missing and non-numeric coordinates (the shape a leaked placeholder would take), out-of-range values, window expiry, and probes that throw or hang."
},
{
"command": "rebuild + reinstall + dumpsys package | grep -c HideTest + am start",
"result": "pass",
"evidence": "0 references in the installed APK. App launches and stays alive with no FATAL entries. dumpsys device_policy still reports Device Owner Type: -1."
}
],
"risks": [
"push_home_location.sh depends on run-as, which only works against a debuggable build. A release APK will need a different channel for the coordinates.",
"The coordinates now exist on the device in plaintext inside app-private storage. That is the same exposure the rooted system already accepted for config_secrets.sh, but it is worth stating: root or a full device backup would reveal them.",
"GuardedWorkoutSignal catches Object deliberately. That is the right call inside an enforcement loop, but it means a genuinely broken Health Connect integration will look identical to 'no workout in progress' - it needs its own logging when that path is implemented.",
"workoutExemptPackages still hardcodes the youtube.com mapping, so a new unblock domain in config.sh will not map to a package by itself.",
"Untouched and still true: DO hiding in user 0 is unproven, and BOOT_COMPLETED does not fire until first unlock."
],
"rollback": [
"git revert. All the new files are additive and nothing outside focus_owner imports them.",
"On the device: adb shell run-as com.kuhy.focus_owner rm -f files/home_location.json removes the provisioned coordinates.",
"After rollback validate: flutter analyze && flutter test pass, and push_home_location.sh --check reports no coordinates provisioned."
]
}

View File

@ -25,42 +25,6 @@ class DevicePolicyBridge(private val context: Context) {
/** Whether this package currently holds device owner. */
fun isDeviceOwner(): Boolean = dpm.isDeviceOwnerApp(context.packageName)
/** Whether this package is profile owner (a work profile, not the device). */
fun isProfileOwner(): Boolean = dpm.isProfileOwnerApp(context.packageName)
/**
* Hides or unhides a package, the DPM equivalent of `pm disable-user`.
*
* This is the mechanism the whole Device Owner design rests on, and unlike
* `pm suspend` and `pm disable-user` — both measured to be cleared by a
* reboot on this device — it is expected to persist. That expectation is
* the thing worth testing before a factory reset is spent on it.
*
* Requires device owner or profile owner; returns false when held by
* neither, rather than throwing.
*/
fun setApplicationHidden(packageName: String, hidden: Boolean): Boolean {
if (!isDeviceOwner() && !isProfileOwner()) {
Log.w(FocusDeviceAdminReceiver.TAG, "not DO/PO; cannot hide $packageName")
return false
}
return runCatching {
val applied = dpm.setApplicationHidden(admin, packageName, hidden)
Log.i(FocusDeviceAdminReceiver.TAG, "setApplicationHidden($packageName,$hidden)=$applied")
applied
}.getOrElse { error ->
Log.e(FocusDeviceAdminReceiver.TAG, "setApplicationHidden failed", error)
false
}
}
/** Whether a package is currently hidden by this admin. */
fun isApplicationHidden(packageName: String): Boolean {
if (!isDeviceOwner() && !isProfileOwner()) return false
return runCatching { dpm.isApplicationHidden(admin, packageName) }
.getOrDefault(false)
}
/** Whether the admin component is active (a weaker state than ownership). */
fun isAdminActive(): Boolean = dpm.isAdminActive(admin)

View File

@ -14,23 +14,6 @@ class MainActivity : FlutterActivity() {
when (call.method) {
"status" -> result.success(bridge.status())
"releaseDeviceOwner" -> result.success(bridge.releaseDeviceOwner())
"setApplicationHidden" -> {
val pkg = call.argument<String>("package")
val hidden = call.argument<Boolean>("hidden")
if (pkg == null || hidden == null) {
result.error("bad_args", "package and hidden required", null)
} else {
result.success(bridge.setApplicationHidden(pkg, hidden))
}
}
"isApplicationHidden" -> {
val pkg = call.argument<String>("package")
if (pkg == null) {
result.error("bad_args", "package required", null)
} else {
result.success(bridge.isApplicationHidden(pkg))
}
}
else -> result.notImplemented()
}
}

View File

@ -1,192 +0,0 @@
import 'dart:math' as math;
import 'package:focus_owner/policy.dart';
/// Why enforcement is currently on or off.
///
/// Carried alongside the decision so the UI and the logs can say *why* an app
/// is hidden. "Blocked" with no reason is the kind of thing that makes a
/// wellbeing tool feel broken rather than deliberate.
enum EnforcementReason {
/// Away from home, so nothing is enforced.
away,
/// At home during the day: the full allowlist applies.
atHome,
/// Inside the curfew window: the much shorter night allowlist applies.
curfew,
/// A workout is in progress, so the workout exceptions are released.
workout,
/// Location is unknown. Treated as "at home" deliberately — see
/// [EnforcementDecision.evaluate].
locationUnknown,
}
/// Inputs to one enforcement decision.
///
/// Grouped into a value type so the decision is a pure function of its inputs
/// and can be tested without a device, a clock, or a location provider.
class EnforcementInputs {
const EnforcementInputs({
required this.installedPackages,
required this.minutesSinceMidnight,
this.latitude,
this.longitude,
this.currentlyEnforcing = false,
this.workoutActive = false,
});
/// Third-party packages present on the device.
final Set<String> installedPackages;
/// Local time, as minutes since midnight.
final int minutesSinceMidnight;
/// Current position, or null when location is unavailable.
final double? latitude;
final double? longitude;
/// Whether enforcement is already active, for geofence hysteresis.
final bool currentlyEnforcing;
/// Whether a workout is in progress.
final bool workoutActive;
}
/// The outcome of evaluating the policy against the current conditions.
class EnforcementDecision {
const EnforcementDecision({
required this.reason,
required this.packagesToHide,
required this.packagesToShow,
});
/// Decides which packages should be hidden right now.
///
/// Fail-closed on unknown location, matching `focus_daemon.sh`, which logs
/// "Location unavailable - defaulting to focus mode". Losing GPS must not be
/// a way to switch enforcement off.
///
/// Note the asymmetry that makes this safe to run unattended: every package
/// the policy allows appears in [packagesToShow] on *every* evaluation, not
/// only on transitions. A missed run therefore leaves apps hidden that
/// should be visible only until the next run, and the next run repairs it
/// without needing to know what the previous one did.
factory EnforcementDecision.evaluate(
FocusPolicy policy,
EnforcementInputs inputs,
) {
final hasFix = inputs.latitude != null && inputs.longitude != null;
final atHome = hasFix &&
_isInside(
policy,
inputs.latitude!,
inputs.longitude!,
currentlyEnforcing: inputs.currentlyEnforcing,
);
if (hasFix && !atHome) {
return EnforcementDecision(
reason: EnforcementReason.away,
packagesToHide: const {},
packagesToShow: inputs.installedPackages,
);
}
final duringCurfew = policy.isCurfewActive(inputs.minutesSinceMidnight);
final reason = !hasFix
? EnforcementReason.locationUnknown
: duringCurfew
? EnforcementReason.curfew
: EnforcementReason.atHome;
final hide = <String>{};
final show = <String>{};
for (final package in inputs.installedPackages) {
if (policy.isAllowed(package, duringCurfew: duringCurfew)) {
show.add(package);
} else {
hide.add(package);
}
}
if (inputs.workoutActive) {
// A workout releases its exception apps from whatever the current
// state would otherwise be, without disturbing anything else.
for (final package in policy.workoutExemptPackages) {
if (hide.remove(package)) show.add(package);
}
return EnforcementDecision(
reason: EnforcementReason.workout,
packagesToHide: hide,
packagesToShow: show,
);
}
return EnforcementDecision(
reason: reason,
packagesToHide: hide,
packagesToShow: show,
);
}
/// Why this decision was reached.
final EnforcementReason reason;
/// Packages that must be hidden.
final Set<String> packagesToHide;
/// Packages that must be visible.
///
/// Always the complete allowed set, never a delta. Unhiding is the failure
/// mode that matters: a system that fails to hide is a mild disappointment,
/// one that fails to unhide strands the user without a dialer or a bank.
final Set<String> packagesToShow;
/// Whether anything is currently restricted.
bool get isEnforcing => packagesToHide.isNotEmpty;
static bool _isInside(
FocusPolicy policy,
double latitude,
double longitude, {
required bool currentlyEnforcing,
}) {
final home = policy.home;
if (!home.hasCoordinates) {
// No coordinates configured: the geofence cannot be evaluated, so it
// must not silently pass. Treated as "at home" by the caller via the
// hasFix path above; here we simply refuse to claim the user is away.
return true;
}
final metres = _haversineMetres(
home.latitude!,
home.longitude!,
latitude,
longitude,
);
final threshold = home.radiusM + (currentlyEnforcing ? home.hysteresisM : 0);
return metres <= threshold;
}
static double _haversineMetres(
double lat1,
double lon1,
double lat2,
double lon2,
) {
const earthRadiusM = 6371000.0;
final dLat = _radians(lat2 - lat1);
final dLon = _radians(lon2 - lon1);
final a = math.pow(math.sin(dLat / 2), 2) +
math.cos(_radians(lat1)) *
math.cos(_radians(lat2)) *
math.pow(math.sin(dLon / 2), 2);
return 2 * earthRadiusM * math.asin(math.sqrt(a.toDouble()));
}
static double _radians(double degrees) => degrees * math.pi / 180.0;
}

View File

@ -1,60 +0,0 @@
import 'dart:convert';
import 'dart:io';
/// The home coordinates, kept out of the committed policy asset.
///
/// `assets/policy.json` ships with `latitude`/`longitude` null so that the
/// repository never records where the user lives. The real values are pushed
/// to the app's private storage at provisioning time by
/// `scripts/push_home_location.sh`, which reads them from the untracked
/// `phone_focus_mode/config_secrets.sh`.
///
/// Private app storage is not world-readable and does not survive an uninstall,
/// which is the right lifetime for this: reinstalling the app should require
/// re-provisioning rather than silently inheriting a stale home.
class HomeLocationStore {
const HomeLocationStore(this.file);
/// Filename written by the provisioning script.
static const String fileName = 'home_location.json';
final File file;
/// Reads the stored coordinates, or null when none have been provisioned.
///
/// Returns null rather than throwing on a malformed or unreadable file. The
/// caller treats an absent home the same way it treats an absent GPS fix —
/// as "cannot determine location", which fails closed into enforcing rather
/// than releasing.
Future<({double latitude, double longitude})?> read() async {
if (!file.existsSync()) return null;
try {
final decoded = jsonDecode(await file.readAsString());
if (decoded is! Map<String, Object?>) return null;
final lat = decoded['latitude'];
final lon = decoded['longitude'];
if (lat is! num || lon is! num) return null;
if (lat.abs() > 90 || lon.abs() > 180) return null;
return (latitude: lat.toDouble(), longitude: lon.toDouble());
} on FormatException {
return null;
} on FileSystemException {
return null;
}
}
/// Writes coordinates, rejecting values that cannot describe a real place.
Future<void> write(double latitude, double longitude) async {
if (latitude.abs() > 90 || longitude.abs() > 180) {
throw ArgumentError('coordinates out of range: $latitude, $longitude');
}
await file.writeAsString(
jsonEncode({'latitude': latitude, 'longitude': longitude}),
);
}
/// Removes any stored coordinates.
Future<void> clear() async {
if (file.existsSync()) await file.delete();
}
}

View File

@ -168,33 +168,6 @@ class FocusPolicy {
/// Whether the curfew is in force at [minutesSinceMidnight].
bool isCurfewActive(int minutesSinceMidnight) =>
curfew?.contains(minutesSinceMidnight) ?? false;
/// Packages released while a workout is in progress.
///
/// The rooted system expressed this exception as *domains*, because it
/// enforced through a hosts file. Hiding apps is a coarser instrument: there
/// is no way to unblock youtube.com without unhiding the YouTube app, so the
/// exception is expressed as packages here.
///
/// Derived from [workoutUnblockDomains] rather than configured separately,
/// so that the shell config stays the single source of truth for *intent*
/// even though the mechanism differs.
Set<String> get workoutExemptPackages {
const domainToPackages = <String, List<String>>{
'youtube.com': [
'com.google.android.youtube',
'com.google.android.apps.youtube.music',
],
};
final packages = <String>{};
for (final entry in domainToPackages.entries) {
final covered = workoutUnblockDomains.any(
(domain) => domain == entry.key || domain.endsWith('.${entry.key}'),
);
if (covered) packages.addAll(entry.value);
}
return packages;
}
}
Set<String> _stringSet(Object? value, String field) {

View File

@ -1,117 +0,0 @@
import 'dart:async';
/// Something that can report whether a workout is currently in progress.
///
/// The rooted system read StrongLifts' SQLite database directly, which an
/// unrooted app cannot do — another app's private storage is unreachable. The
/// replacement is several weaker signals OR'd together.
///
/// Every source must fail *closed*: an error or an unknown state reports "no
/// workout", so a broken source cannot silently unlock YouTube. A source that
/// always returns false is useless but harmless; one that always returns true
/// would quietly disable the exception it exists to gate.
abstract class WorkoutSignal {
/// Short name, for logging and for the UI to explain why YouTube is open.
String get name;
/// Whether this source currently reports a workout in progress.
Future<bool> isActive();
}
/// A workout the user declared, valid for a fixed window.
///
/// The only source that works unconditionally, so it is the fallback the
/// others are layered on top of. It is time-boxed rather than a plain toggle
/// because an untimed "workout mode" left on by accident is indistinguishable
/// from having no exception at all.
class ManualWorkoutSignal implements WorkoutSignal {
ManualWorkoutSignal({
required this.maxDuration,
DateTime Function()? clock,
}) : _clock = clock ?? DateTime.now;
/// How long a declared workout stays valid before it lapses.
final Duration maxDuration;
final DateTime Function() _clock;
DateTime? _startedAt;
@override
String get name => 'manual';
/// Declares a workout as starting now.
void start() => _startedAt = _clock();
/// Ends a declared workout immediately.
void stop() => _startedAt = null;
/// How much of the window remains, or null when no workout is declared.
Duration? get remaining {
final started = _startedAt;
if (started == null) return null;
final left = maxDuration - _clock().difference(started);
return left.isNegative ? null : left;
}
@override
Future<bool> isActive() async => remaining != null;
}
/// A source backed by an asynchronous lookup that may fail.
///
/// Wraps [probe] so that a thrown exception or a timeout reads as "no
/// workout" rather than propagating into the enforcement loop. Used for the
/// Health Connect path, where the query crosses a process boundary and can
/// fail for reasons that have nothing to do with whether the user is training.
class GuardedWorkoutSignal implements WorkoutSignal {
const GuardedWorkoutSignal({
required this.name,
required this.probe,
this.timeout = const Duration(seconds: 5),
});
@override
final String name;
/// The underlying lookup.
final Future<bool> Function() probe;
/// How long to wait before treating the lookup as failed.
final Duration timeout;
@override
Future<bool> isActive() async {
try {
return await probe().timeout(timeout);
} on Object {
// Deliberately broad: this sits in the enforcement loop, and no failure
// of a workout probe should be able to stop enforcement running.
return false;
}
}
}
/// Combines several sources, reporting active if any of them does.
class CombinedWorkoutSignal implements WorkoutSignal {
const CombinedWorkoutSignal(this.sources);
final List<WorkoutSignal> sources;
@override
String get name => 'combined';
/// The name of the first source reporting a workout, or null if none is.
///
/// Exposed so the UI can say *which* signal opened the exception; "YouTube
/// is available because Health Connect sees a session" is far easier to
/// trust, or to disbelieve, than an unexplained unlock.
Future<String?> activeSource() async {
for (final source in sources) {
if (await source.isActive()) return source.name;
}
return null;
}
@override
Future<bool> isActive() async => (await activeSource()) != null;
}

View File

@ -1,144 +0,0 @@
#!/bin/bash
# ============================================================================
# Push the home coordinates into focus_owner's private storage.
#
# Why this exists:
# The geofence needs HOME_LAT/HOME_LON, but those say where the user lives,
# so they are deliberately absent from the committed policy asset - it is
# generated with --redact-home. They live in phone_focus_mode/config_secrets.sh,
# which is gitignored, and are pushed to the device separately.
#
# The file lands in the app's private data directory, which is not
# world-readable and does not survive an uninstall. That is the right
# lifetime: reinstalling should require re-provisioning rather than silently
# inheriting a stale home.
#
# Usage:
# ./push_home_location.sh [--serial <id>] [--secrets <path>] [--check]
# ============================================================================
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
readonly DEFAULT_SERIAL="23181JEGR08034"
readonly PACKAGE="com.kuhy.focus_owner"
readonly REMOTE_NAME="home_location.json"
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
readonly REPO_ROOT
SECRETS="$REPO_ROOT/phone_focus_mode/config_secrets.sh"
SERIAL="$DEFAULT_SERIAL"
CHECK_ONLY=0
log() { printf '[home-loc] %s\n' "$1"; }
die() {
printf '[home-loc] ERROR: %s\n' "$1" >&2
exit 1
}
usage() {
cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS]
--serial <id> adb serial (default: $DEFAULT_SERIAL)
--secrets <path> config_secrets.sh (default: $SECRETS)
--check Report whether coordinates are provisioned; change nothing
-h, --help Show this help
EOF
exit 0
}
adb_sh() { adb -s "$SERIAL" shell "$@" 2>/dev/null | tr -d '\r'; }
require_device() {
command -v adb >/dev/null 2>&1 || die "adb not found; install android-tools"
adb -s "$SERIAL" get-state >/dev/null 2>&1 ||
die "device $SERIAL not connected"
adb_sh "pm list packages $PACKAGE" | grep -q . ||
die "$PACKAGE is not installed on $SERIAL"
}
read_coordinate() {
# Echo one exported coordinate from the secrets file. Deliberately a grep
# rather than sourcing the file: it holds other secrets, and this script
# has no business evaluating them.
local name="$1" raw
raw="$(grep -oP "(?<=^export ${name}=)[^ #]*" "$SECRETS" | tail -1 | tr -d '"'"'"'')"
[[ -n "$raw" ]] || die "$name not found in $SECRETS"
# The shipped secrets file contains REDACTED_* placeholders. Catching that
# here gives a useful message instead of writing a nonsense coordinate that
# would silently put "home" wherever the parse happened to land.
[[ "$raw" =~ ^-?[0-9]+(\.[0-9]+)?$ ]] ||
die "$name is '$raw', not a coordinate - fill in $SECRETS"
printf '%s' "$raw"
}
run_check() {
local out
out="$(adb_sh "run-as $PACKAGE cat files/$REMOTE_NAME")" || true
if [[ -z "$out" ]]; then
log "FAIL no coordinates provisioned"
return 1
fi
# Report presence and shape without echoing the coordinates themselves;
# this output ends up in terminal scrollback and session transcripts.
if grep -q '"latitude"' <<<"$out" && grep -q '"longitude"' <<<"$out"; then
log "OK coordinates provisioned (${#out} bytes)"
return 0
fi
log "FAIL provisioned file is malformed"
return 1
}
main() {
require_device
if [[ $CHECK_ONLY -eq 1 ]]; then
run_check
exit $?
fi
[[ -f "$SECRETS" ]] || die "secrets file not found: $SECRETS"
local lat lon tmp
lat="$(read_coordinate HOME_LAT)"
lon="$(read_coordinate HOME_LON)"
tmp="$(mktemp)"
# shellcheck disable=SC2064 # expand $tmp now, not at trap time
trap "rm -f '$tmp'" EXIT
printf '{"latitude": %s, "longitude": %s}\n' "$lat" "$lon" >"$tmp"
# Staged via /data/local/tmp because adb push cannot write into another
# app's private directory; run-as then moves it in as the app's own uid.
adb -s "$SERIAL" push "$tmp" "/data/local/tmp/$REMOTE_NAME" >/dev/null ||
die "adb push failed"
# chmod 600 because the default umask leaves it 666. The directory is
# already private, so this is belt-and-braces rather than the only barrier,
# but a world-writable file holding the geofence anchor is worth avoiding.
adb_sh "run-as $PACKAGE sh -c 'mkdir -p files && cat /data/local/tmp/$REMOTE_NAME > files/$REMOTE_NAME && chmod 600 files/$REMOTE_NAME'" ||
die "run-as failed - is this a debuggable build?"
adb_sh "rm -f /data/local/tmp/$REMOTE_NAME"
log "Coordinates written to $PACKAGE private storage"
run_check
}
while [[ $# -gt 0 ]]; do
case $1 in
--serial)
SERIAL="$2"
shift 2
;;
--secrets)
SECRETS="$2"
shift 2
;;
--check)
CHECK_ONLY=1
shift
;;
-h | --help) usage ;;
*) die "Unknown option: $1" ;;
esac
done
main "$@"

View File

@ -1,276 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:focus_owner/enforcement.dart';
import 'package:focus_owner/policy.dart';
/// Warsaw, used only as a fixed reference point for the geofence maths.
const double _homeLat = 52.2297;
const double _homeLon = 21.0122;
const double _metresPerDegreeLat = 111320;
FocusPolicy _policy({bool withCoordinates = true, Object? curfew}) =>
FocusPolicy.fromJson({
'schema_version': kSupportedSchemaVersion,
'home': {
'latitude': withCoordinates ? _homeLat : null,
'longitude': withCoordinates ? _homeLon : null,
'radius_m': 150.0,
'hysteresis_m': 30.0,
},
'curfew': curfew ?? const {'start': '23:00', 'end': '05:00'},
'launcher_package': 'com.launcher',
'allowed_packages': [
'com.launcher',
'pl.mbank',
'com.discord',
'com.google.android.youtube',
],
'night_allowed_packages': ['com.launcher', 'pl.mbank'],
'never_disable_prefixes': ['com.android.settings'],
'workout_unblock_domains': ['youtube.com', 'googlevideo.com'],
'browser_packages': <String>[],
});
const _installed = {
'com.launcher',
'pl.mbank',
'com.discord',
'com.google.android.youtube',
'com.evil',
'com.android.settings',
};
/// A point [metres] north of home.
double _latOffset(double metres) => _homeLat + metres / _metresPerDegreeLat;
void main() {
group('away from home', () {
test('nothing is hidden and everything is shown', () {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _latOffset(5000),
longitude: _homeLon,
),
);
expect(decision.reason, EnforcementReason.away);
expect(decision.packagesToHide, isEmpty);
expect(decision.packagesToShow, _installed);
expect(decision.isEnforcing, isFalse);
});
});
group('at home during the day', () {
late EnforcementDecision decision;
setUp(() {
decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _homeLat,
longitude: _homeLon,
),
);
});
test('only non-allowlisted apps are hidden', () {
expect(decision.reason, EnforcementReason.atHome);
expect(decision.packagesToHide, {'com.evil'});
});
test('protected system packages are never hidden', () {
expect(decision.packagesToShow, contains('com.android.settings'));
});
test('the launcher is never hidden', () {
expect(decision.packagesToShow, contains('com.launcher'));
});
});
group('curfew', () {
test('the night list is much shorter than the day list', () {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 23 * 60 + 30,
latitude: _homeLat,
longitude: _homeLon,
),
);
expect(decision.reason, EnforcementReason.curfew);
expect(decision.packagesToHide, containsAll(['com.discord', 'com.evil']));
expect(decision.packagesToShow, containsAll(['pl.mbank', 'com.launcher']));
});
test('curfew wraps past midnight', () {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 3 * 60,
latitude: _homeLat,
longitude: _homeLon,
),
);
expect(decision.reason, EnforcementReason.curfew);
});
test('after the curfew ends the day list applies again', () {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 6 * 60,
latitude: _homeLat,
longitude: _homeLon,
),
);
expect(decision.reason, EnforcementReason.atHome);
expect(decision.packagesToShow, contains('com.discord'));
});
});
group('geofence hysteresis', () {
// 160m is outside the 150m radius but inside radius+hysteresis (180m), so
// the answer must depend on the current state or the enforcer flaps.
EnforcementDecision at160m({required bool enforcing}) =>
EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _latOffset(160),
longitude: _homeLon,
currentlyEnforcing: enforcing,
),
);
test('arriving: not yet inside', () {
expect(at160m(enforcing: false).reason, EnforcementReason.away);
});
test('leaving: still inside', () {
expect(at160m(enforcing: true).reason, EnforcementReason.atHome);
});
test('well beyond the band is away in both states', () {
for (final enforcing in [true, false]) {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _latOffset(500),
longitude: _homeLon,
currentlyEnforcing: enforcing,
),
);
expect(decision.reason, EnforcementReason.away);
}
});
});
group('fail-closed behaviour', () {
test('unknown location enforces rather than releasing', () {
// Losing GPS must not be a way to switch enforcement off. Matches
// focus_daemon.sh, which defaults to focus mode when location fails.
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
),
);
expect(decision.reason, EnforcementReason.locationUnknown);
expect(decision.packagesToHide, contains('com.evil'));
});
test('a policy with redacted coordinates still enforces', () {
// The committed policy.json has no coordinates. That must not silently
// disable the geofence into "always away".
final decision = EnforcementDecision.evaluate(
_policy(withCoordinates: false),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _latOffset(5000),
longitude: _homeLon,
),
);
expect(decision.packagesToHide, contains('com.evil'));
});
});
group('workout exception', () {
test('releases YouTube without releasing anything else', () {
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 23 * 60 + 30,
latitude: _homeLat,
longitude: _homeLon,
workoutActive: true,
),
);
expect(decision.reason, EnforcementReason.workout);
expect(decision.packagesToShow, contains('com.google.android.youtube'));
expect(decision.packagesToHide, contains('com.evil'));
expect(decision.packagesToHide, contains('com.discord'));
});
test('domains map to packages, since hiding cannot target a domain', () {
expect(
_policy().workoutExemptPackages,
contains('com.google.android.youtube'),
);
});
test('no workout domains means no exempt packages', () {
final policy = FocusPolicy.fromJson({
'schema_version': kSupportedSchemaVersion,
'home': {
'latitude': null,
'longitude': null,
'radius_m': 150.0,
'hysteresis_m': 30.0,
},
'curfew': null,
'launcher_package': null,
'allowed_packages': <String>[],
'night_allowed_packages': <String>[],
'never_disable_prefixes': <String>[],
'workout_unblock_domains': <String>[],
'browser_packages': <String>[],
});
expect(policy.workoutExemptPackages, isEmpty);
});
});
group('unhide reliability', () {
test('packagesToShow is the full allowed set, not a delta', () {
// The service applies packagesToShow unconditionally on every run, so a
// missed evaluation self-repairs. A delta would require knowing what the
// previous run did, and a reboot loses that.
final decision = EnforcementDecision.evaluate(
_policy(),
EnforcementInputs(
installedPackages: _installed,
minutesSinceMidnight: 12 * 60,
latitude: _homeLat,
longitude: _homeLon,
),
);
final union = {...decision.packagesToHide, ...decision.packagesToShow};
expect(union, _installed);
expect(
decision.packagesToHide.intersection(decision.packagesToShow),
isEmpty,
);
});
});
}

View File

@ -1,87 +0,0 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:focus_owner/home_location.dart';
void main() {
late Directory dir;
late HomeLocationStore store;
setUp(() {
dir = Directory.systemTemp.createTempSync('home_loc_test');
store = HomeLocationStore(File('${dir.path}/${HomeLocationStore.fileName}'));
});
tearDown(() => dir.deleteSync(recursive: true));
group('read', () {
test('returns null when nothing is provisioned', () async {
expect(await store.read(), isNull);
});
test('round-trips written coordinates', () async {
await store.write(52.2297, 21.0122);
final read = await store.read();
expect(read?.latitude, closeTo(52.2297, 1e-9));
expect(read?.longitude, closeTo(21.0122, 1e-9));
});
test('returns null on malformed JSON rather than throwing', () async {
// A corrupt file must read as "location unknown", which the enforcement
// layer treats as fail-closed. Throwing here would crash the service.
await store.file.writeAsString('not json at all');
expect(await store.read(), isNull);
});
test('returns null when the document is not an object', () async {
await store.file.writeAsString('[1, 2, 3]');
expect(await store.read(), isNull);
});
test('returns null when a coordinate is missing', () async {
await store.file.writeAsString('{"latitude": 52.2}');
expect(await store.read(), isNull);
});
test('returns null when a coordinate is not a number', () async {
// This is the shape the shipped REDACTED_* placeholder would produce if
// it ever reached the device.
await store.file
.writeAsString('{"latitude": "REDACTED_LAT", "longitude": 21.0}');
expect(await store.read(), isNull);
});
test('returns null for out-of-range coordinates', () async {
await store.file.writeAsString('{"latitude": 91.0, "longitude": 21.0}');
expect(await store.read(), isNull);
});
});
group('write', () {
test('rejects an impossible latitude', () {
expect(() => store.write(91, 0), throwsArgumentError);
});
test('rejects an impossible longitude', () {
expect(() => store.write(0, 181), throwsArgumentError);
});
test('accepts the poles and the antimeridian', () async {
await store.write(90, 180);
expect((await store.read())?.latitude, 90);
});
});
group('clear', () {
test('removes provisioned coordinates', () async {
await store.write(52.2297, 21.0122);
await store.clear();
expect(await store.read(), isNull);
});
test('is a no-op when nothing is stored', () async {
await store.clear();
expect(await store.read(), isNull);
});
});
}

View File

@ -1,125 +0,0 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:focus_owner/workout_signal.dart';
/// A source with a fixed answer, for exercising the combinator.
class _Fixed implements WorkoutSignal {
const _Fixed(this.name, this.value);
@override
final String name;
final bool value;
@override
Future<bool> isActive() async => value;
}
void main() {
group('ManualWorkoutSignal', () {
late DateTime now;
late ManualWorkoutSignal signal;
setUp(() {
now = DateTime(2026, 8, 9, 12);
signal = ManualWorkoutSignal(
maxDuration: const Duration(minutes: 90),
clock: () => now,
);
});
test('is inactive until a workout is declared', () async {
expect(await signal.isActive(), isFalse);
expect(signal.remaining, isNull);
});
test('is active once started', () async {
signal.start();
expect(await signal.isActive(), isTrue);
expect(signal.remaining, const Duration(minutes: 90));
});
test('lapses when the window expires', () async {
// Time-boxed rather than a plain toggle: a "workout mode" left on by
// accident is indistinguishable from having no exception at all.
signal.start();
now = now.add(const Duration(minutes: 89));
expect(await signal.isActive(), isTrue);
now = now.add(const Duration(minutes: 2));
expect(await signal.isActive(), isFalse);
expect(signal.remaining, isNull);
});
test('stop ends it immediately', () async {
signal.start();
signal.stop();
expect(await signal.isActive(), isFalse);
});
test('restarting extends the window from the new start', () async {
signal.start();
now = now.add(const Duration(minutes: 80));
signal.start();
expect(signal.remaining, const Duration(minutes: 90));
});
});
group('GuardedWorkoutSignal', () {
test('passes through a successful probe', () async {
const signal = GuardedWorkoutSignal(name: 'hc', probe: _alwaysTrue);
expect(await signal.isActive(), isTrue);
});
test('a throwing probe reads as no workout', () async {
// Fail closed: a broken probe must not unlock YouTube.
const signal = GuardedWorkoutSignal(name: 'hc', probe: _alwaysThrows);
expect(await signal.isActive(), isFalse);
});
test('a hanging probe times out to no workout', () async {
const signal = GuardedWorkoutSignal(
name: 'hc',
probe: _neverCompletes,
timeout: Duration(milliseconds: 50),
);
expect(await signal.isActive(), isFalse);
});
});
group('CombinedWorkoutSignal', () {
test('is inactive when every source is', () async {
const combined = CombinedWorkoutSignal([
_Fixed('a', false),
_Fixed('b', false),
]);
expect(await combined.isActive(), isFalse);
expect(await combined.activeSource(), isNull);
});
test('is active when any source is', () async {
const combined = CombinedWorkoutSignal([
_Fixed('a', false),
_Fixed('b', true),
]);
expect(await combined.isActive(), isTrue);
});
test('names the source that opened the exception', () async {
// So the UI can explain the unlock rather than presenting it as magic.
const combined = CombinedWorkoutSignal([
_Fixed('manual', false),
_Fixed('health_connect', true),
]);
expect(await combined.activeSource(), 'health_connect');
});
test('with no sources it is inactive', () async {
const combined = CombinedWorkoutSignal([]);
expect(await combined.isActive(), isFalse);
});
});
}
Future<bool> _alwaysTrue() async => true;
Future<bool> _alwaysThrows() async => throw StateError('probe failed');
Future<bool> _neverCompletes() => Completer<bool>().future;