fix: allow recording outside protected fields

This commit is contained in:
Зарубин Филипп
2026-09-14 05:10:38 +03:00
parent 07aa70b379
commit 0fceb1ebbf
13 changed files with 5277 additions and 4808 deletions
+1 -1
View File
@@ -1 +1 @@
0.2.2
0.2.3
+10 -2
View File
@@ -313,7 +313,14 @@ public final class DictationController {
hotkeys.isRecordingActive = { [weak self] in self?.isRecording ?? false }
hotkeys.canStartRecording = { [weak self] in
guard let self else { return false }
return self.startRefusal() == nil
// Только предварительный допуск по состоянию. AX не вызывается
// внутри event tap: полная проверка идёт в handlePress, до микрофона,
// после dispatchHotkeyActions на главный актор.
return dictationStartRefusal(modelReady: self.modelReady,
isRecording: self.isRecording,
isBusy: self.isBusy,
secureInputActive: false,
modelWarming: self.modelWarming) == nil
}
}
@@ -645,7 +652,8 @@ public final class DictationController {
isRecording: isRecording,
isBusy: isBusy,
secureInputActive: Permissions.isSecureInputActive,
modelWarming: modelWarming)
modelWarming: modelWarming,
focusedInputProtected: Permissions.focusedInputProtection)
}
/// Смена аудиоустройства посреди записи: крючок AudioCapture до этого
+14 -4
View File
@@ -171,8 +171,8 @@ let dictationWarmUpWaitLimitSeconds: Double = 180
// MARK: - Отказ старта записи
/// Почему запись не стартует. `secureInputActive` — новый класс отказа:
/// в поле пароля синтетический ⌘V не дойдёт всё равно, честнее сказать сразу.
/// Почему запись не стартует. Защита относится к текущему полю, а не к
/// наличию фонового процесса с защищённым вводом клавиатуры.
enum DictationStartRefusal: String, Equatable {
case secureInputActive
case modelNotReady
@@ -180,6 +180,12 @@ enum DictationStartRefusal: String, Equatable {
case transcriptionInFlight
}
/// Неизвестное поле при активной системной защите не считается обычным.
func dictationInputIsProtected(secureInputActive: Bool,
focusedInputProtected: Bool?) -> Bool {
focusedInputProtected ?? secureInputActive
}
/// Отказать ли старту.
///
/// `modelWarming` отделяет «модель ещё грузится» от «модели нет». Разница
@@ -195,8 +201,12 @@ func dictationStartRefusal(modelReady: Bool,
isRecording: Bool,
isBusy: Bool,
secureInputActive: Bool,
modelWarming: Bool = false) -> DictationStartRefusal? {
if secureInputActive { return .secureInputActive }
modelWarming: Bool = false,
focusedInputProtected: Bool? = nil) -> DictationStartRefusal? {
if dictationInputIsProtected(secureInputActive: secureInputActive,
focusedInputProtected: focusedInputProtected) {
return .secureInputActive
}
if !modelReady, !modelWarming { return .modelNotReady }
if isRecording { return .alreadyRecording }
if isBusy { return .transcriptionInFlight }
@@ -98,12 +98,17 @@ func dictationLearningReadFocusedText() -> (text: String, pid: pid_t)? {
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
let pid = app.processIdentifier
let axApp = AXUIElementCreateApplication(pid)
AXUIElementSetMessagingTimeout(axApp, 0.15)
var focusedRaw: AnyObject?
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
&focusedRaw) == .success,
let focused = focusedRaw else { return nil }
let focused = focusedRaw,
CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
let element = focused as! AXUIElement
// Проверяем именно этот элемент до AXValue. Неизвестное состояние —
// тоже отказ: для обучения читать потенциально защищённый текст незачем.
guard Permissions.inputProtection(of: element) == false else { return nil }
var roleRaw: AnyObject?
AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRaw)
+8 -7
View File
@@ -160,7 +160,8 @@ struct HotkeyTransitionState {
/// `canStartRecording` mirrors the app-side guard on handlePress
/// (ready, not recording, not busy, not terminating). Toggle mode
/// consults it before claiming either recording route.
/// consults it only before claiming a recording route. Ordinary keyboard
/// events must not trigger the app's potentially expensive AX query.
mutating func transition(
for event: HotkeyEventSnapshot,
hotkey: HotkeyChoice,
@@ -177,7 +178,7 @@ struct HotkeyTransitionState {
translationHotkeyEnabled: Bool = false,
triggerMode: TriggerMode,
isRecording: Bool,
canStartRecording: Bool = true
canStartRecording: @autoclosure () -> Bool = true
) -> HotkeyTransitionResult {
if event.keycode == ESCAPE_KEYCODE {
return transitionEscape(for: event, isRecording: isRecording)
@@ -278,7 +279,7 @@ struct HotkeyTransitionState {
// in toggle mode because the state machine gates it here.
guard !isRecording,
activeRecordingRoute == nil,
canStartRecording else {
canStartRecording() else {
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
actions: [.rejectedBusyPress])
}
@@ -291,7 +292,7 @@ struct HotkeyTransitionState {
private mutating func transitionPromptShortcut(
for event: HotkeyEventSnapshot,
isRecording: Bool,
canStartRecording: Bool,
canStartRecording: () -> Bool,
promptHotkey: HotkeyChoice,
triggerMode: TriggerMode
) -> HotkeyTransitionResult? {
@@ -338,7 +339,7 @@ struct HotkeyTransitionState {
}
guard !isRecording,
activeRecordingRoute == nil,
canStartRecording else {
canStartRecording() else {
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
actions: [.rejectedBusyPress])
}
@@ -352,7 +353,7 @@ struct HotkeyTransitionState {
private mutating func transitionTranslationShortcut(
for event: HotkeyEventSnapshot,
isRecording: Bool,
canStartRecording: Bool,
canStartRecording: () -> Bool,
translationHotkey: HotkeyChoice,
triggerMode: TriggerMode
) -> HotkeyTransitionResult? {
@@ -399,7 +400,7 @@ struct HotkeyTransitionState {
}
guard !isRecording,
activeRecordingRoute == nil,
canStartRecording else {
canStartRecording() else {
return HotkeyTransitionResult(suppress: shortcutResult.suppress,
actions: [.rejectedBusyPress])
}
+49 -6
View File
@@ -26,14 +26,57 @@ enum Permissions {
}
}
/// Активен ли защищённый ввод — поле пароля, Secure Keyboard Entry в
/// терминале. Тот же системный вызов, что у AutoSwitchPolicy в IrizInput
/// (тянуть IrizInput в IrizDictate не за чем — API системное).
///
/// Для диктовки это честный класс провала вставки: в защищённое поле
/// синтетический ⌘V не дойдёт всё равно, а сырьё уже легло бы на диск.
/// Глобальная защита клавиатурных событий: её может держать фоновый
/// процесс. Сама по себе она не описывает поле в фокусе и не запрещает микрофон.
static var isSecureInputActive: Bool { IsSecureEventInputEnabled() }
static var isDictationInputProtected: Bool {
dictationInputIsProtected(secureInputActive: isSecureInputActive,
focusedInputProtected: focusedInputProtection)
}
/// Только метаданные текущего элемента; содержимое поля не запрашивается.
/// Неизвестное состояние сохраняется как nil для осторожного fallback.
static var focusedInputProtection: Bool? {
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
let axApp = AXUIElementCreateApplication(app.processIdentifier)
AXUIElementSetMessagingTimeout(axApp, 0.15)
var focused: CFTypeRef?
guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString,
&focused) == .success,
let focused, CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil }
return inputProtection(of: focused as! AXUIElement)
}
static func inputProtection(of element: AXUIElement) -> Bool? {
AXUIElementSetMessagingTimeout(element, 0.15)
return inputProtection { attribute in
var value: CFTypeRef?
let error = AXUIElementCopyAttributeValue(element, attribute, &value)
return (error, value)
}
}
/// Тот же путь чтения в продукте и в пробе: проба не касается чужого окна.
static func inputProtection(readAttribute: (CFString) -> (AXError, CFTypeRef?)) -> Bool? {
let (roleError, roleValue) = readAttribute(kAXRoleAttribute as CFString)
let (subroleError, subroleValue) = readAttribute(kAXSubroleAttribute as CFString)
if subroleError == .success, subroleValue as? String == kAXSecureTextFieldSubrole { return true }
let (protectedError, protectedValue) = readAttribute(
NSAccessibility.Attribute.containsProtectedContent.rawValue as CFString)
if protectedError == .success, protectedValue as? Bool == true { return true }
// Необязательного атрибута может не быть у обычного поля/окна.
// Таймаут и ошибка связи отсутствием атрибута не считаются.
// Явная защита выше ошибки роли: её нельзя потерять при частичном ответе AX.
guard roleError == .success, let role = roleValue as? String, !role.isEmpty else { return nil }
let optionalAbsent: [AXError] = [.attributeUnsupported, .noValue]
guard (subroleError == .success && subroleValue is String) || optionalAbsent.contains(subroleError),
(protectedError == .success && protectedValue is Bool) || optionalAbsent.contains(protectedError)
else { return nil }
return false
}
/// Trigger the system prompt or, if previously denied, push the
/// user toward the right Settings pane. Returns immediately;
/// actual grant happens asynchronously.
+8 -4
View File
@@ -103,7 +103,8 @@ func postKeyboardEventSteps(_ steps: [KeyboardEventStep], targetPID: pid_t? = ni
enum KeyboardShortcutPoster {
@discardableResult
static func postReturn() -> Bool {
postKeyboardEventSteps([
guard TextInserter.targetAllowsPosting(nil) else { return false }
return postKeyboardEventSteps([
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: true, flags: []),
KeyboardEventStep(virtualKey: RETURN_KEYCODE, keyDown: false, flags: []),
])
@@ -188,10 +189,13 @@ enum TextInserter {
}
fileprivate static func targetAllowsPosting(_ expectedTargetPID: pid_t?) -> Bool {
textInsertionTargetAllowsPosting(
guard let checkedPID = NSWorkspace.shared.frontmostApplication?.processIdentifier,
textInsertionTargetAllowsPosting(
expectedTargetPID: expectedTargetPID,
currentTargetPID: NSWorkspace.shared.frontmostApplication?.processIdentifier
)
currentTargetPID: checkedPID
), !Permissions.isDictationInputProtected else { return false }
// AX — IPC: за время проверки фокус мог перейти к другому приложению.
return NSWorkspace.shared.frontmostApplication?.processIdentifier == checkedPID
}
}
@@ -425,6 +425,35 @@ struct HungTranscriptionTests {
@Suite("dictationStartRefusal")
struct DictationStartRefusalTests {
@Test func backgroundSecureKeyboardInputDoesNotBlockOrdinaryFieldRecording() {
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
isBusy: false, secureInputActive: true,
focusedInputProtected: false) == nil)
}
@Test func actualProtectedFieldBlocksEvenWithoutGlobalKeyboardFlag() {
for globalSecureInput in [false, true] {
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
isBusy: false, secureInputActive: globalSecureInput,
focusedInputProtected: true) == .secureInputActive)
}
}
@Test func ordinaryFieldRetainsModelAndBusyGuards() {
#expect(dictationStartRefusal(modelReady: false, isRecording: false,
isBusy: false, secureInputActive: true,
focusedInputProtected: false) == .modelNotReady)
#expect(dictationStartRefusal(modelReady: false, isRecording: false,
isBusy: false, secureInputActive: true,
modelWarming: true, focusedInputProtected: false) == nil)
#expect(dictationStartRefusal(modelReady: true, isRecording: true,
isBusy: false, secureInputActive: true,
focusedInputProtected: false) == .alreadyRecording)
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
isBusy: true, secureInputActive: true,
focusedInputProtected: false) == .transcriptionInFlight)
}
/// Защищённый ввод: запись не стартует, причина названа — звонит отказ.
@Test func secureInputBlocksRecording() {
#expect(dictationStartRefusal(modelReady: true,
@@ -0,0 +1,88 @@
import AppKit
import ApplicationServices
import Testing
@testable import IrizDictate
@Suite("Защита поля не равна глобальной защите клавиатуры")
@MainActor
struct FocusedInputProtectionTests {
private func protection(role: String? = "AXTextField",
roleError: AXError = .success,
subrole: String? = nil,
subroleError: AXError = .attributeUnsupported,
protected: Bool? = nil,
protectedError: AXError = .attributeUnsupported) -> Bool? {
Permissions.inputProtection { attribute in
switch attribute as String {
case kAXRoleAttribute:
return (roleError, role.map { $0 as CFString })
case kAXSubroleAttribute:
return (subroleError, subrole.map { $0 as CFString })
case NSAccessibility.Attribute.containsProtectedContent.rawValue:
return (protectedError, protected.map { NSNumber(value: $0) })
default:
Issue.record("Неожиданный запрос атрибута: \(attribute)")
return (.attributeUnsupported, nil)
}
}
}
@Test func парольЗащищёнПриЛюбомГлобальномФлаге() {
let focused = protection(subrole: kAXSecureTextFieldSubrole, subroleError: .success)
#expect(focused == true)
for global in [false, true] {
#expect(dictationInputIsProtected(secureInputActive: global, focusedInputProtected: focused))
}
}
@Test func защищённоеСодержимоеНеТребуетПарольнойПодроли() {
#expect(protection(role: "AXTextArea", protected: true, protectedError: .success) == true)
#expect(protection(subroleError: .cannotComplete,
protected: true, protectedError: .success) == true)
#expect(protection(roleError: .cannotComplete,
protected: true, protectedError: .success) == true)
#expect(protection(roleError: .cannotComplete,
subrole: kAXSecureTextFieldSubrole, subroleError: .success) == true)
}
@Test func обычноеПолеИОкноНеБлокируютсяФоновымФлагом() {
for role in ["AXTextField", "AXTextArea", "AXWindow"] {
let focused = protection(role: role)
#expect(focused == false)
#expect(!dictationInputIsProtected(secureInputActive: true, focusedInputProtected: focused))
}
#expect(protection(role: "AXWindow", subrole: "AXStandardWindow", subroleError: .success,
protected: false, protectedError: .success) == false)
#expect(protection(subroleError: .noValue, protectedError: .noValue) == false)
}
@Test func ошибкаИОтсутствующаяРольОставляютСостояниеНеизвестным() {
for error: AXError in [.cannotComplete, .invalidUIElement, .attributeUnsupported, .noValue] {
#expect(protection(roleError: error) == nil)
}
#expect(protection(role: nil) == nil)
#expect(protection(role: "") == nil)
#expect(protection(subroleError: .cannotComplete) == nil)
#expect(protection(protectedError: .cannotComplete) == nil)
#expect(protection(subroleError: .success) == nil)
#expect(protection(protectedError: .success) == nil)
#expect(dictationInputIsProtected(secureInputActive: true, focusedInputProtected: nil))
#expect(!dictationInputIsProtected(secureInputActive: false, focusedInputProtected: nil))
}
@Test func запросОграниченМетаданнымиБезЗначенияИВыделения() {
var requested: [String] = []
let result = Permissions.inputProtection { attribute in
let name = attribute as String
requested.append(name)
if name == kAXRoleAttribute { return (.success, "AXTextArea" as CFString) }
return (.attributeUnsupported, nil)
}
#expect(result == false)
#expect(requested == [kAXRoleAttribute, kAXSubroleAttribute,
NSAccessibility.Attribute.containsProtectedContent.rawValue])
#expect(!requested.contains(kAXValueAttribute))
#expect(!requested.contains(kAXSelectedTextAttribute))
}
}
+41
View File
@@ -168,6 +168,47 @@ struct HotkeyAutomatonTests {
#expect(result.suppress)
}
@Test func readinessIsLazyForEveryToggleRecordingRoute() {
let routes: [(CGKeyCode, HotkeyTransitionAction, HotkeyTransitionAction)] = [
(96, .press, .release),
(97, .pressPrompt, .releasePrompt),
(98, .pressTranslation, .releaseTranslation),
]
for (keycode, start, stop) in routes {
var state = HotkeyTransitionState()
var readinessCalls = 0
func ready() -> Bool {
readinessCalls += 1
return true
}
func send(_ type: CGEventType, _ keycode: CGKeyCode,
isRecording: Bool = false) -> HotkeyTransitionResult {
state.transition(for: keyEvent(type, keycode),
hotkey: hotkeyChoice(forKeycode: 96),
historyHotkey: hotkeyChoice(forKeycode: 100),
promptHotkey: hotkeyChoice(forKeycode: 97),
promptHotkeyEnabled: true,
translationHotkey: hotkeyChoice(forKeycode: 98),
translationHotkeyEnabled: true,
triggerMode: .toggle,
isRecording: isRecording,
canStartRecording: ready())
}
#expect(send(.keyDown, 0).actions.isEmpty)
#expect(send(.keyUp, 0).actions.isEmpty)
#expect(send(.keyDown, 100).actions == [.showHistory])
_ = send(.keyUp, 100)
#expect(readinessCalls == 0)
#expect(send(.keyDown, keycode).actions == [start])
#expect(readinessCalls == 1)
_ = send(.keyUp, keycode, isRecording: true)
#expect(readinessCalls == 1)
#expect(send(.keyDown, keycode, isRecording: true).actions == [stop])
#expect(readinessCalls == 1)
}
}
@Test func toggleReleaseIsNoOpButSuppressed() {
var state = HotkeyTransitionState()
_ = state.transition(for: flagsChanged(54, .maskCommand),
+16
View File
@@ -0,0 +1,16 @@
# iriz 0.2.3 — кандидат выпуска
Исправление ложного отказа запуска записи. Выпуск ещё не опубликован.
- Фоновый защищённый ввод клавиатуры больше не запрещает запись, когда
метаданные текущего элемента подтверждают обычное поле или окно.
- Настоящее парольное поле и защищённое содержимое проверяются отдельно,
в том числе перед вставкой текста и отложенным Enter.
- Обучение не читает значение защищённого или недоступного элемента.
- Если текущий элемент недоступен для проверки, активная системная защита
по-прежнему запрещает запуск и автоматическую вставку.
Системная защита macOS и защита автоматического исправления клавиатуры
не отключаются. Движок распознавания и захват звука не заменены. В установленной
сборке 0.2.3 пройдено несколько живых циклов «микрофон → распознавание → вставка».
Опубликованный DMG 0.2.2 не перезаписывается.
File diff suppressed because it is too large Load Diff
+4556 -4268
View File
File diff suppressed because it is too large Load Diff