onionwire/src/sanitize.rs
Sirius DevOps e3738c51f7
Some checks failed
ci / test (pull_request) Failing after 2m2s
[verified] sanitize peer chat/control/bidi before store and TUI render
Strip C0 (except tab/newline), DEL, C1, and bidi/format marks at ingest
and render; keep ZWJ; lossy UTF-8 stays U+FFFD. Reject the same set in
fil names. Docs match the policy.
2026-09-11 23:42:48 -04:00

44 lines
1.3 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Strip terminal/UI-injection characters from untrusted peer text.
//!
//! Chat is not required to be valid UTF-8 (invalid bytes become U+FFFD).
//! After lossy decode, these code points are removed:
//! - C0 0x00–0x1F except `\t` and `\n`, plus DEL (0x7F)
//! - C1 U+0080–U+009F
//! - bidi/format: U+202A–U+202E, U+2066–U+2069, U+200E, U+200F
//! - zero-width: U+200B (ZWSP), U+200C (ZWNJ)
//!
//! U+200D (ZWJ) is kept so emoji ZWJ sequences stay intact.
use std::borrow::Cow;
pub fn display_text(bytes: &[u8]) -> Cow<'_, str> {
match std::str::from_utf8(bytes) {
Ok(s) if !s.chars().any(is_stripped) => Cow::Borrowed(s),
Ok(s) => Cow::Owned(filter_stripped(s)),
Err(_) => Cow::Owned(filter_stripped(&String::from_utf8_lossy(bytes))),
}
}
/// True for C0/C1 controls and bidi/format marks (including `\t`/`\n`).
pub fn is_control_or_bidi(c: char) -> bool {
matches!(
c,
'\0'..='\u{1f}'
| '\u{7f}'
| '\u{80}'..='\u{9f}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
| '\u{200e}'
| '\u{200f}'
| '\u{200b}'
| '\u{200c}'
)
}
fn is_stripped(c: char) -> bool {
c != '\t' && c != '\n' && is_control_or_bidi(c)
}
fn filter_stripped(s: &str) -> String {
s.chars().filter(|c| !is_stripped(*c)).collect()
}