import 'dart:convert'; import 'package:flutter/services.dart' show AssetBundle, rootBundle; /// Schema version this build understands. /// /// The asset is generated by `python3 -m python_pkg.focus_policy`, which is the /// single source of truth. Refusing an unknown version is deliberate: silently /// accepting a newer schema would mean enforcing a policy this code has /// misread, and a misread allowlist is an allowlist that blocks the dialer. const int kSupportedSchemaVersion = 1; /// Raised when the bundled policy cannot be trusted. class PolicyFormatException implements Exception { const PolicyFormatException(this.message); final String message; @override String toString() => 'PolicyFormatException: $message'; } /// A nightly window that may wrap midnight (23:00 -> 05:00). class CurfewWindow { const CurfewWindow({required this.startMinutes, required this.endMinutes}); /// Parses an `{"start": "23:00", "end": "05:00"}` object. factory CurfewWindow.fromJson(Map json) { return CurfewWindow( startMinutes: _parseHhMm(json['start'], 'curfew.start'), endMinutes: _parseHhMm(json['end'], 'curfew.end'), ); } /// Minutes since midnight. final int startMinutes; final int endMinutes; /// Whether [minutesSinceMidnight] falls inside the window. /// /// Wrapping windows are the normal case here, so "inside" means at or after /// the start *or* before the end, not both. bool contains(int minutesSinceMidnight) { if (startMinutes <= endMinutes) { return minutesSinceMidnight >= startMinutes && minutesSinceMidnight < endMinutes; } return minutesSinceMidnight >= startMinutes || minutesSinceMidnight < endMinutes; } } /// The home anchor. Coordinates are null in a redacted policy. class HomeLocation { const HomeLocation({ required this.latitude, required this.longitude, required this.radiusM, required this.hysteresisM, }); /// Parses the `home` object. factory HomeLocation.fromJson(Map json) { return HomeLocation( latitude: (json['latitude'] as num?)?.toDouble(), longitude: (json['longitude'] as num?)?.toDouble(), radiusM: _requireNum(json['radius_m'], 'home.radius_m'), hysteresisM: _requireNum(json['hysteresis_m'], 'home.hysteresis_m'), ); } final double? latitude; final double? longitude; final double radiusM; final double hysteresisM; /// Whether this policy carries real coordinates. /// /// The committed asset is redacted, so the location gate cannot run against /// it. Enforcement must check this rather than treating a missing coordinate /// as (0, 0), which would put "home" in the Atlantic. bool get hasCoordinates => latitude != null && longitude != null; } /// The device-independent focus policy, as generated from `config.sh`. class FocusPolicy { const FocusPolicy({ required this.home, required this.allowedPackages, required this.nightAllowedPackages, required this.neverDisablePrefixes, required this.workoutUnblockDomains, required this.curfew, required this.launcherPackage, }); /// Parses a rendered policy document. factory FocusPolicy.fromJson(Map json) { final version = json['schema_version']; if (version != kSupportedSchemaVersion) { throw PolicyFormatException( 'unsupported schema_version $version ' '(this build understands $kSupportedSchemaVersion)', ); } final home = json['home']; if (home is! Map) { throw const PolicyFormatException('missing "home" object'); } final curfew = json['curfew']; return FocusPolicy( home: HomeLocation.fromJson(home), allowedPackages: _stringSet(json['allowed_packages'], 'allowed_packages'), nightAllowedPackages: _stringSet(json['night_allowed_packages'], 'night_allowed_packages'), neverDisablePrefixes: _stringSet( json['never_disable_prefixes'], 'never_disable_prefixes', ), workoutUnblockDomains: _stringSet( json['workout_unblock_domains'], 'workout_unblock_domains', ), curfew: curfew == null ? null : CurfewWindow.fromJson(curfew as Map), launcherPackage: json['launcher_package'] as String?, ); } /// Loads the policy bundled with the app. static Future load({ AssetBundle? bundle, String assetKey = 'assets/policy.json', }) async { final raw = await (bundle ?? rootBundle).loadString(assetKey); final decoded = jsonDecode(raw); if (decoded is! Map) { throw const PolicyFormatException('policy asset is not a JSON object'); } return FocusPolicy.fromJson(decoded); } final HomeLocation home; final Set allowedPackages; final Set nightAllowedPackages; final Set neverDisablePrefixes; final Set workoutUnblockDomains; final CurfewWindow? curfew; final String? launcherPackage; /// Whether a package must never be disabled. /// /// Prefix-matched on whole labels, so `com.android.providers` covers /// `com.android.providers.telephony` but not `com.android.providersomething`. bool isProtected(String package) => neverDisablePrefixes.any( (prefix) => package == prefix || package.startsWith('$prefix.'), ); /// Whether a package may run under the given conditions. bool isAllowed(String package, {bool duringCurfew = false}) { if (isProtected(package)) return true; return duringCurfew ? nightAllowedPackages.contains(package) : allowedPackages.contains(package); } /// 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 get workoutExemptPackages { const domainToPackages = >{ 'youtube.com': [ 'com.google.android.youtube', 'com.google.android.apps.youtube.music', ], }; final packages = {}; 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 _stringSet(Object? value, String field) { if (value is! List) { throw PolicyFormatException('"$field" must be a list'); } return value.map((e) => e! as String).toSet(); } double _requireNum(Object? value, String field) { if (value is! num) { throw PolicyFormatException('"$field" must be a number'); } return value.toDouble(); } int _parseHhMm(Object? value, String field) { if (value is! String) { throw PolicyFormatException('"$field" must be a "HH:MM" string'); } final parts = value.split(':'); if (parts.length != 2) { throw PolicyFormatException('"$field" must be "HH:MM", got "$value"'); } final hour = int.tryParse(parts[0]); final minute = int.tryParse(parts[1]); if (hour == null || minute == null || hour > 23 || minute > 59) { throw PolicyFormatException('"$field" is not a valid time: "$value"'); } return hour * 60 + minute; }