Skip to content
Merged
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
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@ can replace a verified pre-caret span in supported Unicode Edit controls. Unknow
controls, unsafe selections and security refusals skip correction and log only
failure metadata.

**App Rules** adds layered terminal/editor safety. New terminal and editor rules
disable manual, word-count and character triggers. Enable **Manual** explicitly;
editors also require **Editor prose**. **Safety** defaults to automatic detection,
or can classify a custom app as `terminal` or `code_editor`. Known apps cannot be
downgraded by choosing `auto`.

Manual requests in these apps require selected prose. Heuristics reject commands,
flags, paths, URLs, identifiers, code and uncertain fragments before either engine
runs. Editor automatic correction requires explicit trigger and prose opt-ins,
and a whole segment of recognizable line-comment prose. Terminal automatic
requests still skip because the shell context cannot be proven safe.
Existing permissions survive migration; the new editor prose permission starts
off. Selected results still skip native replacement until caret-end proof is
available, and manual-only rules do not enable continuous typed-input capture.

## Run App

From the repository root, build and run AutoFix:
Expand Down
28 changes: 28 additions & 0 deletions app-core-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,34 @@ context/executable/caret-anchor versions, trigger, engine kind, and correction m
Grammar, language, confidence, dictionary, and API settings are snapshotted for
engine execution. Following selected text stays informative.

Terminal/editor text safety lives in `background/security/text_safety`.
SQLite app rules store `safety_mode` (`auto`, `terminal`, `code_editor`) and
`prose_context_allowed` (false by default). Schema v5 adds these fields without
changing existing trigger/engine choices; legacy IPC payloads default to auto/off.
Fresh and reset editor rules now default manual correction to off too. Known
process names and terminal/editor title heuristics enforce conservative defaults
even after a rule is deleted. Custom profiles classify other applications;
known terminal/editor identities cannot be downgraded to general text fields.

Restricted manual requests require selection, explicit manual permission and,
for editors, explicit prose permission. Admission recognizes only conservative
English sentence shapes, with at least three words, sentence punctuation and a
prose function word. Structured punctuation, identifiers, commands, paths, URLs,
mixed prose/code and unclear surrounding lines refuse the entire request.
Uncertain languages and fragments skip. Editor automatic requests additionally
require their trigger permission and complete `//` or `#` line-comment sentences;
inline/block comments are unsupported. Terminal automatic text requests skip
because the shell dialect and prompt state are unknown. Manual-only rules never
authorize tracking or final-fix triggers. Selected results retain the existing
native replacement refusal until the live caret end can be proven.

Admission reads app rules through a fresh, nonblocking read-only connection without
migrations or writer reservations. API sends and native replacement recheck the
same text policy under their existing writer reservations, so a committed prose
revocation prevents further sends or mutation. Neither logs nor skip notices include
the rejected text. Hard secure-field gates, dictionary policy, clipboard preservation,
session ownership and undo remain enforced.

Frozen results survive processed typing and backspace confined to the new active
context. The tracker retains the original typed ranges and supplies the replacement
owner with the known following text up to the current caret, which must be verified
Expand Down
6 changes: 3 additions & 3 deletions app-core-rust/src/background/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,9 +472,9 @@ impl InputProcessor {
context_capture::read_before_caret(target, &config.context, known_chars)
},
|target, request, output| {
let Some(_policy_guard) =
SecurityGate::authorize_replacement(request.trigger, config, database, target)
else {
let Some(_policy_guard) = SecurityGate::authorize_correction_replacement(
request, config, database, target,
) else {
tracing::warn!(
success = false,
method = "none",
Expand Down
26 changes: 25 additions & 1 deletion app-core-rust/src/background/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,30 @@ impl CorrectionPipeline {
config: &AppConfig,
dictionary: Vec<String>,
) -> bool {
// Check executable text before either local execution or API transmission.
if let Some(path) = self.database_path.as_deref() {
let allowed =
crate::storage::AppPolicyGuard::read_rules_nowait(path).is_ok_and(|rules| {
matches!(
super::security::check_detection(
request.trigger,
config,
&rules,
super::target::TargetDetection::Available(target.clone())
),
super::security::SecurityDecision::Allowed { .. }
) && super::security::request_allowed(&rules, &target, &request)
});
if !allowed {
self.feedback_event = Some((
Event::Blocked,
request.trigger == TriggerKind::ManualShortcut,
));
return false;
}
} else if !super::security::request_allowed(&[], &target, &request) {
return false;
}
if request.pending_segment_id.is_none() {
self.cancel();
}
Expand All @@ -203,7 +227,7 @@ impl CorrectionPipeline {
self.database_path.clone(),
config.clone(),
target.clone(),
request.trigger,
request.clone(),
Arc::clone(&cancelled),
);
let input = CorrectionInput {
Expand Down
60 changes: 60 additions & 0 deletions app-core-rust/src/background/pipeline/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,64 @@ const STAMP: InputStamp = InputStamp {
sequence: 12,
};

/// Both routes refuse restricted content before dispatch; refusal preserves session ownership.
#[test]
fn restricted_text_never_reaches_either_correction_engine() {
let path = std::env::temp_dir().join(format!(
"autofix-text-safety-{}-{}.sqlite",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let database = crate::storage::Database::open(&path).unwrap();
for process in ["cmd.exe", "code.exe"] {
let mut rule = database
.app_rules()
.list()
.unwrap()
.into_iter()
.find(|rule| rule.process_name == process)
.unwrap();
rule.manual_shortcut_allowed = true;
rule.prose_context_allowed = true;
database.app_rules().upsert(&rule).unwrap();
for engine in [
crate::settings::CorrectionEngine::Local,
crate::settings::CorrectionEngine::Api,
] {
let mut config = AppConfig::default();
config.correction.engine = engine;
let mut restricted_target = target();
restricted_target.process_name = process.into();
let manager = manager(&config, "This is user_name.");
let mut request = request(&manager, &config);
request.selected_text = true;
let mut pipeline =
CorrectionPipeline::start(|_| panic!("unsafe text reached correction engine"))
.unwrap();
pipeline.database_path = Some(path.clone());
assert!(!pipeline.submit(
request,
manager.active().unwrap(),
restricted_target,
STAMP,
&config,
vec![]
));
assert!(pipeline.active.is_empty());
assert!(pipeline.mailbox.0.lock().unwrap().jobs.is_empty());
assert_eq!(
manager.active().unwrap().editable_context(),
"This is user_name."
);
}
}
drop(database);
std::fs::remove_file(path).unwrap();
}

/// Unavailable exclusion storage refuses submission without dispatching work or changing session text.
#[test]
fn unavailable_exclusions_refuse_submission_without_storage_side_effects() {
Expand Down Expand Up @@ -344,6 +402,8 @@ fn queued_api_job_is_denied_after_rule_revocation_and_releases_its_slot() {
character_trigger_allowed: true,
local_engine_allowed: true,
api_engine_allowed: false,
safety_mode: "auto".into(),
prose_context_allowed: false,
})
.unwrap();
wait_completion(&pipeline);
Expand Down
31 changes: 26 additions & 5 deletions app-core-rust/src/background/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use crate::{
use super::target::{self, CorrectionEligibility, FocusedTarget, TargetDetection};

mod outbound;
mod text_safety;
pub(super) use outbound::api_send_authorization;
pub(super) use text_safety::request_allowed;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TriggerKind {
Expand Down Expand Up @@ -48,6 +50,17 @@ pub(crate) enum BlockReason {
pub(crate) struct SecurityGate;

impl SecurityGate {
/// Revalidate prose opt-in and text heuristics under the mutation reservation.
pub(super) fn authorize_correction_replacement(
request: &super::triggers::CorrectionRequest,
config: &AppConfig,
database: &Database,
target: &FocusedTarget,
) -> Option<AppPolicyGuard> {
let guard = Self::authorize_replacement(request.trigger, config, database, target)?;
request_allowed(&guard.rules().ok()?, target, request).then_some(guard)
}

/// Keep the current app rules stable through native mutation and verification.
/// Missing/busy storage refuses replacement before any selection or input.
pub(super) fn authorize_replacement(
Expand Down Expand Up @@ -127,8 +140,12 @@ pub(crate) fn check_detection(
};
}

// TODO: Once typed-session executable text is available here, block command
// lines, filesystem paths, URLs, and code-like text before app rules.
if !text_safety::trigger_allowed(app_rules, &target, trigger) {
return SecurityDecision::Blocked {
reason: BlockReason::AppRuleBlocked,
target: Some(target),
};
}
let matching_rule = matching_rule(app_rules, &target);
if let Some(rule) = matching_rule.filter(|rule| !trigger_allowed(rule, trigger)) {
let _ = rule;
Expand Down Expand Up @@ -248,9 +265,7 @@ fn trigger_allowed(rule: &AppRule, trigger: TriggerKind) -> bool {
TriggerKind::WordCount => rule.word_count_trigger_allowed,
TriggerKind::Character => rule.character_trigger_allowed,
TriggerKind::FinalFixBeforeReanchor => {
rule.manual_shortcut_allowed
|| rule.word_count_trigger_allowed
|| rule.character_trigger_allowed
rule.word_count_trigger_allowed || rule.character_trigger_allowed
}
TriggerKind::Undo => rule.manual_shortcut_allowed,
}
Expand Down Expand Up @@ -454,6 +469,8 @@ mod tests {
character_trigger_allowed: true,
local_engine_allowed: true,
api_engine_allowed: true,
safety_mode: "auto".into(),
prose_context_allowed: false,
}
}

Expand Down Expand Up @@ -554,6 +571,8 @@ mod tests {
character_trigger_allowed: false,
local_engine_allowed: false,
api_engine_allowed: false,
safety_mode: "auto".into(),
prose_context_allowed: false,
..allow_rule(process_name)
}
}
Expand All @@ -568,6 +587,8 @@ mod tests {
character_trigger_allowed: false,
local_engine_allowed: true,
api_engine_allowed: true,
safety_mode: "auto".into(),
prose_context_allowed: false,
}
}

Expand Down
Loading
Loading