grammargem/Sources/GrammaGem/System/Exclusions.swift
BigMarc 35ae2065b3 Fix 22 audited bugs: stop hangs/crashes/text-corruption; auto-install model
Stability (the "super buggy" feel):
- Move the Accessibility-tree traversal OFF the main thread with a per-message
  timeout, so a busy/wedged target app can't beachball or hang GrammaGem.
- Replace every unchecked `as! AXUIElement` force-cast with a CFTypeID-checked
  safe cast (AXSupport), eliminating crashes from misbehaving AX servers.
- Never scan GrammaGem's own windows (self-PID exclusion).
- Generation tokens + in-flight guard so superseded scans/downloads can't clobber state.

Text safety:
- Live fixes now read the element's CURRENT value before writing (and only apply a
  span edit when the field still matches the snapshot), so edits made since the last
  scan are never overwritten. Cap per-field check length.
- Stable per-field identity (AX id / position) so the Live Check list no longer churns.
- Include focus + identity in change-detection so tabbing updates the focused field.

Other audited fixes:
- Page blocker: conservative skip when a browser's URL can't be read.
- Model download: validate on-disk size (reject HTML/truncated 200s), clean up
  partials on cancel/failure, handle URLError.cancelled.
- Licensing: clear a server-confirmed-invalid license instead of honoring grace;
  show the real device limit instead of "0 Macs".
- Hotkey re-register falls back to the default if a chosen combo is taken.
- Daily free-tier counter tracks the live timezone.
- "Fix focused field" ignores non-text controls.

Feature: auto-install the on-device model in the background on first launch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:08:35 +02:00

89 lines
3.3 KiB
Swift

import Foundation
import AppKit
/// The "page blocker": apps and domains where GrammaGem should stay completely
/// out of the way — password managers, banking sites, anything sensitive.
/// When the frontmost context is excluded, live monitoring and the hotkeys are
/// suppressed.
@MainActor
final class Exclusions: ObservableObject {
@Published private(set) var blockedApps: [String] // bundle identifiers
@Published private(set) var blockedDomains: [String] // hostnames, e.g. "chase.com"
private let appsKey = "GrammaGem.blockedApps"
private let domainsKey = "GrammaGem.blockedDomains"
private let d = UserDefaults.standard
/// Common sensitive apps offered as one-tap suggestions in the UI.
static let suggestedApps: [(name: String, bundleID: String)] = [
("1Password", "com.1password.1password"),
("Bitwarden", "com.bitwarden.desktop"),
("Keychain Access", "com.apple.keychainaccess"),
("Terminal", "com.apple.Terminal"),
]
init() {
blockedApps = d.stringArray(forKey: appsKey) ?? []
blockedDomains = d.stringArray(forKey: domainsKey) ?? []
}
/// True if the user has any domain rules (so we should be conservative when
/// a browser's URL can't be read).
var hasDomainRules: Bool { !blockedDomains.isEmpty }
/// Whether GrammaGem should be suppressed for this frontmost context.
func isBlocked(bundleID: String?, domain: String?) -> Bool {
if let bundleID, blockedApps.contains(bundleID) { return true }
if let host = domain?.lowercased(), !host.isEmpty {
return blockedDomains.contains { dom in
let d = dom.lowercased()
return host == d || host.hasSuffix("." + d)
}
}
return false
}
func addApp(_ bundleID: String) {
let b = bundleID.trimmingCharacters(in: .whitespaces)
guard !b.isEmpty, !blockedApps.contains(b) else { return }
blockedApps.append(b)
d.set(blockedApps, forKey: appsKey)
}
func removeApp(_ bundleID: String) {
blockedApps.removeAll { $0 == bundleID }
d.set(blockedApps, forKey: appsKey)
}
func addDomain(_ domain: String) {
let host = normalizedDomain(domain)
guard !host.isEmpty, !blockedDomains.contains(host) else { return }
blockedDomains.append(host)
d.set(blockedDomains, forKey: domainsKey)
}
func removeDomain(_ domain: String) {
blockedDomains.removeAll { $0 == domain }
d.set(blockedDomains, forKey: domainsKey)
}
/// Friendly app name for a bundle id, if installed.
func appName(for bundleID: String) -> String {
if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID),
let bundle = Bundle(url: url),
let name = (bundle.infoDictionary?["CFBundleName"] as? String) {
return name
}
return bundleID
}
private func normalizedDomain(_ raw: String) -> String {
var s = raw.trimmingCharacters(in: .whitespaces).lowercased()
if let url = URL(string: s), let host = url.host { return host }
s = s.replacingOccurrences(of: "https://", with: "")
.replacingOccurrences(of: "http://", with: "")
if let slash = s.firstIndex(of: "/") { s = String(s[..<slash]) }
return s
}
}