Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Normal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
membershipExceptions = (
BlockingUITests.swift,
DonationUITests.swift,
EditProtectionUITests.swift,
NormalUITests.swift,
NormalUITestsLaunchTests.swift,
RecoveryUITests.swift,
Expand All @@ -130,6 +131,7 @@
membershipExceptions = (
BlockingUITests.swift,
DonationUITests.swift,
EditProtectionUITests.swift,
NormalUITests.swift,
NormalUITestsLaunchTests.swift,
RecoveryUITests.swift,
Expand Down
3 changes: 3 additions & 0 deletions Normal/App/AppContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ struct AppContainer: View {
@State private var emergencyUnblockService: EmergencyUnblockService
@State private var donationService = DonationService()
@State private var usageLimitService: UsageLimitService
@State private var editSessionService: EditSessionService
@State private var unlockInbox: UnlockRequestInbox

init(services: AppServices) {
Expand All @@ -21,6 +22,7 @@ struct AppContainer: View {
_appReviewService = State(initialValue: services.appReview)
_emergencyUnblockService = State(initialValue: services.emergencyUnblock)
_usageLimitService = State(initialValue: services.usageLimit)
_editSessionService = State(initialValue: services.editSession)
_unlockInbox = State(initialValue: services.unlockInbox)
}

Expand All @@ -37,6 +39,7 @@ struct AppContainer: View {
.environment(emergencyUnblockService)
.environment(donationService)
.environment(usageLimitService)
.environment(editSessionService)
.environment(unlockInbox)
}
}
5 changes: 5 additions & 0 deletions Normal/App/AppServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ final class AppServices {
let appReview: AppReviewService
let emergencyUnblock: EmergencyUnblockService
let usageLimit: UsageLimitService
let editSession: EditSessionService
let unlockInbox = UnlockRequestInbox()

init() {
Expand Down Expand Up @@ -47,6 +48,9 @@ final class AppServices {
sharedStore: store,
ledger: InMemoryUsageLimitLedger()
)
editSession = EditSessionService(
defaults: UserDefaults(suiteName: "uitest-edit-\(UUID().uuidString)")!
)
} else {
let screenTime = ScreenTimeService()
self.screenTime = screenTime
Expand All @@ -55,6 +59,7 @@ final class AppServices {
appReview = AppReviewService()
emergencyUnblock = EmergencyUnblockService(ledger: KeychainEmergencyUnblockLedger())
usageLimit = UsageLimitService()
editSession = EditSessionService()
}
}
}
4 changes: 4 additions & 0 deletions Normal/App/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ struct ContentView: View {
@Environment(ScheduleService.self) private var scheduleService
@Environment(EmergencyUnblockService.self) private var emergencyUnblockService
@Environment(UsageLimitService.self) private var usageLimitService
@Environment(EditSessionService.self) private var editSessionService
@Environment(\.scenePhase) private var scenePhase
@Query private var allSettings: [Settings]
@Query private var schedules: [BlockSchedule]
Expand All @@ -23,6 +24,7 @@ struct ContentView: View {
var body: some View {
ZStack {
MainTabView(selectedTab: $navigationCoordinator.selectedTab)
.editUnblockHost()
if onboardingService.isOnboardingActive {
OnboardingOverlayView()
}
Expand All @@ -45,6 +47,7 @@ struct ContentView: View {
if newPhase == .active {
Task { await screenTimeService.checkAuthorizationStatus() }
screenTimeService.notifyUpdate()
editSessionService.refresh()
timedUnblockService.refresh(screenTimeService: screenTimeService)
// The monitor extension may have spent a limit while we were away.
usageLimitService.notifyUpdate()
Expand All @@ -60,6 +63,7 @@ struct ContentView: View {
scheduleService.mirrorCustomDomainsEnabled(settings.enableCustomDomains)
}

editSessionService.refresh()
timedUnblockService.reconcile(screenTimeService: screenTimeService)
if settings?.hasCompletedOnboarding == true {
onboardingService.isOnboardingActive = false
Expand Down
3 changes: 3 additions & 0 deletions Normal/App/NormalApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ struct NormalApp: App {
settings.skipBlockWithoutKeyConfirmation = UITestSupport.skipBypassConfirm
settings.customUnblockDurationSeconds = UITestSupport.unblockDurationSeconds
settings.defaultUnblockSeconds = UITestSupport.defaultDurationSeconds
if let editMode = UITestSupport.editProtectionMode {
settings.editProtectionMode = editMode
}
context.insert(settings)
}

Expand Down
3 changes: 3 additions & 0 deletions Normal/App/UITestSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ enum UITestSupport {

static let defaultDurationSeconds: Int? = value(after: "-uiTestDefaultDuration").flatMap(Int.init)

static let editProtectionMode: EditProtectionMode? = value(after: "-uiTestEditProtection")
.flatMap(EditProtectionMode.init(rawValue:))

static let stubScanValue = "UITEST-SCAN-VALUE"

static let mainSelection = selection(apps: websitesOnly ? [] : [1, 2, 3])
Expand Down
40 changes: 40 additions & 0 deletions Normal/Models/EditProtectionMode.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Foundation

enum EditProtectionMode: String, CaseIterable, Identifiable, Hashable, Sendable {
case unblockAll = "unblockAll"
case requireKey = "requireKey"

var id: String { rawValue }

var label: String {
switch self {
case .unblockAll: String(localized: "When All Apps Unblocked")
case .requireKey: String(localized: "With a Key")
}
}

var shortLabel: String {
switch self {
case .unblockAll: String(localized: "All Unblocked")
case .requireKey: String(localized: "With a Key")
}
}

var description: String {
switch self {
case .unblockAll:
String(localized: "Editing is available whenever no apps are blocked.")
case .requireKey:
String(localized: "Scan a global key to unblock editing. Blocked apps stay blocked.")
}
}

var footer: String {
switch self {
case .unblockAll:
String(localized: "When a schedule unblocks all apps, editing becomes available without a key.")
case .requireKey:
String(localized: "Protects apps, groups, schedules, and keys even when no apps are blocked.")
}
}
}
98 changes: 98 additions & 0 deletions Normal/Models/EditProtectionPolicy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import Foundation

nonisolated enum EditSessionState: Equatable, Sendable {
case blocked
case timed(endDate: Date)
case permanent
}

nonisolated enum EditProtectionState: Equatable, Sendable {
case open
case sessionActive(endDate: Date?)
case requiresKey
case requiresUnblockAll

var isBlocked: Bool {
switch self {
case .open, .sessionActive: false
case .requiresKey, .requiresUnblockAll: true
}
}
}

enum EditProtectionPolicy {
static func hasUsableGlobalKey(
in keys: [Key],
availableKeyTypes: [KeyType] = KeyType.availableOnDevice
) -> Bool {
let globalTypes = keys.filter(\.isGlobal).map(\.type)
return !KeyType.selectable(registered: globalTypes, onDevice: availableKeyTypes).isEmpty
}

static func state(
mode: EditProtectionMode,
session: EditSessionState,
keys: [Key],
activeShieldCount: @autoclosure () -> Int,
allowWhenNoKeys: Bool = false,
now: Date = .now,
availableKeyTypes: [KeyType] = KeyType.availableOnDevice
) -> EditProtectionState {
switch mode {
case .requireKey:
switch session {
case .permanent:
return .sessionActive(endDate: nil)
case .timed(let endDate) where endDate > now:
return .sessionActive(endDate: endDate)
case .blocked, .timed:
break
}
if hasUsableGlobalKey(in: keys, availableKeyTypes: availableKeyTypes) {
return .requiresKey
}
return fallbackUnblockAllState(
keys: keys,
activeShieldCount: activeShieldCount(),
allowWhenNoKeys: allowWhenNoKeys
)
case .unblockAll:
return fallbackUnblockAllState(
keys: keys,
activeShieldCount: activeShieldCount(),
allowWhenNoKeys: allowWhenNoKeys
)
}
}

static func modeChangeAccess(
from current: EditProtectionMode,
to target: EditProtectionMode,
session: EditSessionState,
keys: [Key],
activeShieldCount: @autoclosure () -> Int = 0,
now: Date = .now,
availableKeyTypes: [KeyType] = KeyType.availableOnDevice
) -> EditProtectionState {
guard current == .requireKey, target == .unblockAll else { return .open }
return state(
mode: current,
session: session,
keys: keys,
activeShieldCount: activeShieldCount(),
now: now,
availableKeyTypes: availableKeyTypes
)
}

private static func fallbackUnblockAllState(
keys: [Key],
activeShieldCount: @autoclosure () -> Int,
allowWhenNoKeys: Bool
) -> EditProtectionState {
if allowWhenNoKeys, keys.isEmpty {
return .open
}
return activeShieldCount() > 0 ? .requiresUnblockAll : .open
}
}
61 changes: 61 additions & 0 deletions Normal/Models/Settings+EditProtection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Foundation

extension Settings {
var editProtectionMode: EditProtectionMode {
get {
editProtectionRawValue.flatMap(EditProtectionMode.init(rawValue:)) ?? .unblockAll
}
set {
editProtectionRawValue = newValue.rawValue
}
}

var editDurationOverride: DefaultOverride<TimedUnblockDuration> {
get {
guard overridesEditDefaultDuration else { return .appDefault }
return
editDefaultUnblockSeconds
.flatMap(TimedUnblockDuration.init(validating:))
.map(DefaultOverride.value) ?? .none
}
set {
overridesEditDefaultDuration = newValue != .appDefault
if case .value(let duration) = newValue {
editDefaultUnblockSeconds = duration.seconds
} else {
editDefaultUnblockSeconds = nil
}
}
}

var editKeyOverride: DefaultOverride<KeyType> {
get {
guard overridesEditDefaultKey else { return .appDefault }
return editDefaultKeyType.map(DefaultOverride.value) ?? .none
}
set {
overridesEditDefaultKey = newValue != .appDefault
if case .value(let keyType) = newValue {
editDefaultKeyType = keyType
} else {
editDefaultKeyType = nil
}
}
}

var resolvedEditDefaultDuration: TimedUnblockDuration? {
switch editDurationOverride {
case .appDefault: defaultDuration
case .none: nil
case .value(let duration): unblockDurations.contains(duration) ? duration : nil
}
}

var resolvedEditDefaultKeyType: KeyType? {
switch editKeyOverride {
case .appDefault: defaultKeyType
case .none: nil
case .value(let keyType): keyType
}
}
}
5 changes: 5 additions & 0 deletions Normal/Models/Settings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ final class Settings {
var enableCustomDomains: Bool = false
var skipBlockWithoutKeyConfirmation: Bool = false
var dailyLimitResetMinutes: Int = 0
var editProtectionRawValue: String?
var overridesEditDefaultDuration: Bool = false
var editDefaultUnblockSeconds: Int?
var overridesEditDefaultKey: Bool = false
var editDefaultKeyType: KeyType?

static let maxEmergencyUnblocks = 3
private static let emergencyWindowDays = 180
Expand Down
2 changes: 1 addition & 1 deletion Normal/Models/UnblockLength.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

enum UnblockLength: Equatable {
enum UnblockLength: Equatable, Hashable, Sendable {
case timed(TimedUnblockDuration)
case permanent
}
Loading