Probe Windows terminal colors without risking startup input (#40598)

## Why

Windows Terminal and xterm.js can render a theme that differs from the
underlying console color table. Querying that visible theme through OSC shares
the console input queue with keystrokes, including input for security-sensitive
startup prompts.

## What changed

- Defer the Windows OSC color probe until protected startup decisions and the
  world-writable workspace scan have completed.
- Preserve and replay unrelated console input records around the probe, while
  removing only valid OSC 10 and 11 replies and retaining the console palette
  as a fallback.
- Require an explicit confirmation key after shortcuts select trust, sandbox,
  or world-writable warning choices, so a fragmented terminal reply cannot
  accept them.
- Accept one- through four-digit OSC RGB components so the visible terminal
  palette is applied across supported response formats.

## Testing

Added coverage for delayed startup scans, protected prompt confirmation,
console-record replay, bracketed paste and malformed OSC preservation, RGB
response parsing, and light-theme composer rendering.

GitOrigin-RevId: b8ae456fe32c701ba3af31e9cc452fc4e8bffa22
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-08-25 12:20:41 +00:00
1 parent 1f5c9ba183
commit 70b5cfc73b
19 files changed
+1162 -149

No files matched your search

+335
View File
@@ -0,0 +1,335 @@
//! Probe visible Windows terminal colors without consuming startup typeahead.
use super::DefaultColors;
use super::windows_replay::terminal_color_response_ranges;
use super::windows_replay::terminal_default_colors;
use std::io;
use std::io::ErrorKind;
use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::Storage::FileSystem::WriteFile;
use windows_sys::Win32::System::Console::CONSOLE_SCREEN_BUFFER_INFOEX;
use windows_sys::Win32::System::Console::GetConsoleScreenBufferInfoEx;
use windows_sys::Win32::System::Console::GetNumberOfConsoleInputEvents;
use windows_sys::Win32::System::Console::GetStdHandle;
use windows_sys::Win32::System::Console::INPUT_RECORD;
use windows_sys::Win32::System::Console::KEY_EVENT;
use windows_sys::Win32::System::Console::ReadConsoleInputW;
use windows_sys::Win32::System::Console::STD_INPUT_HANDLE;
use windows_sys::Win32::System::Console::STD_OUTPUT_HANDLE;
use windows_sys::Win32::System::Console::WriteConsoleInputW;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
const MAX_WINDOWS_PROBE_RECORDS: usize = 64 * 1_024;
const WINDOWS_PROBE_READ_RECORDS: usize = 64;
/// Prefer the terminal renderer's OSC colors while retaining the native console palette fallback.
///
/// Windows Terminal and xterm.js can render a theme unrelated to ConPTY's console color table.
/// Their OSC responses share the input queue with user input, so the probe preserves and restores
/// the original console records without changing Windows' input-record mode.
pub(crate) fn default_colors(timeout: Duration) -> io::Result<Option<DefaultColors>> {
let Ok(output) = std_handle(STD_OUTPUT_HANDLE) else {
return Ok(None);
};
if let Ok(input) = std_handle(STD_INPUT_HANDLE)
&& let Ok(Some(colors)) = query_osc_default_colors(input, output, timeout)
{
tracing::debug!(
foreground = ?colors.fg,
background = ?colors.bg,
"using Windows terminal OSC default colors"
);
return Ok(Some(colors));
}
let colors = query_console_default_colors(output).ok().flatten();
if let Some(colors) = colors {
tracing::debug!(
foreground = ?colors.fg,
background = ?colors.bg,
"using Windows console palette default colors"
);
}
Ok(colors)
}
fn query_osc_default_colors(
input: HANDLE,
output: HANDLE,
timeout: Duration,
) -> io::Result<Option<DefaultColors>> {
let deadline = Instant::now() + timeout;
write_all(output, b"\x1b]10;?\x1b\\\x1b]11;?\x1b\\")?;
let mut replay = ConsoleInputReplay::new(input);
let result = replay.read_until(deadline);
let replay_result = replay.replay();
replay_result?;
result
}
/// Preserve native console records and map response bytes back to their original records.
#[derive(Default)]
struct BufferedConsoleInput {
records: Vec<INPUT_RECORD>,
bytes: Vec<u8>,
byte_record_indices: Vec<usize>,
}
impl BufferedConsoleInput {
fn push(&mut self, record: INPUT_RECORD) {
let index = self.records.len();
self.records.push(record);
if record.EventType != KEY_EVENT as u16 {
return;
}
// SAFETY: EventType identifies the active INPUT_RECORD union member.
let key = unsafe { record.Event.KeyEvent };
if key.bKeyDown == 0 {
return;
}
// SAFETY: ReadConsoleInputW populates the UnicodeChar member of KEY_EVENT_RECORD.
let character = unsafe { key.uChar.UnicodeChar };
if let Ok(byte) = u8::try_from(character)
&& byte.is_ascii()
&& byte != 0
{
self.bytes.push(byte);
self.byte_record_indices.push(index);
}
}
fn preserved_records(&self) -> Vec<INPUT_RECORD> {
let mut omitted = vec![false; self.records.len()];
for response in terminal_color_response_ranges(&self.bytes) {
for byte_index in response {
let record_index = self.byte_record_indices[byte_index];
omitted[record_index] = true;
}
}
self.records
.iter()
.copied()
.enumerate()
.filter_map(|(index, record)| (!omitted[index]).then_some(record))
.collect()
}
}
/// Replay every non-response console event even when probing exits through an error path.
struct ConsoleInputReplay {
handle: HANDLE,
input: BufferedConsoleInput,
replayed_records: usize,
}
impl ConsoleInputReplay {
fn new(handle: HANDLE) -> Self {
Self {
handle,
input: BufferedConsoleInput::default(),
replayed_records: 0,
}
}
fn read_until(&mut self, deadline: Instant) -> io::Result<Option<DefaultColors>> {
loop {
if let Some(colors) = terminal_default_colors(&self.input.bytes) {
return Ok(Some(colors));
}
if self.input.records.len() >= MAX_WINDOWS_PROBE_RECORDS {
return Ok(None);
}
let now = Instant::now();
if now >= deadline {
return Ok(None);
}
let timeout_ms = deadline
.saturating_duration_since(now)
.as_millis()
.min(u32::MAX as u128) as u32;
match unsafe {
WaitForSingleObject(self.handle, timeout_ms.max(/*other*/ 1))
} {
WAIT_OBJECT_0 => {
self.read_available()?;
}
WAIT_TIMEOUT => return Ok(None),
_ => return Err(io::Error::last_os_error()),
}
}
}
fn read_available(&mut self) -> io::Result<usize> {
let mut pending = 0;
if unsafe { GetNumberOfConsoleInputEvents(self.handle, &mut pending) } == 0 {
return Err(io::Error::last_os_error());
}
if pending == 0 {
return Ok(0);
}
let mut records =
[unsafe { std::mem::zeroed::<INPUT_RECORD>() }; WINDOWS_PROBE_READ_RECORDS];
let max_records = records
.len()
.min(pending as usize)
.min(MAX_WINDOWS_PROBE_RECORDS.saturating_sub(self.input.records.len()));
if max_records == 0 {
return Ok(0);
}
let mut read = 0;
let result = unsafe {
ReadConsoleInputW(
self.handle,
records.as_mut_ptr(),
max_records as u32,
&mut read,
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
for record in records.into_iter().take(read as usize) {
self.input.push(record);
}
Ok(read as usize)
}
fn replay(&mut self) -> io::Result<()> {
if self.input.records.is_empty() {
return Ok(());
}
if self.replayed_records == 0 {
// WriteConsoleInputW appends, so include already queued later records before restoring
// the earlier records. Preserve one bounded queue snapshot without waiting on input.
let mut pending = 0;
if unsafe { GetNumberOfConsoleInputEvents(self.handle, &mut pending) } == 0 {
return Err(io::Error::last_os_error());
}
let mut remaining = (pending as usize)
.min(MAX_WINDOWS_PROBE_RECORDS.saturating_sub(self.input.records.len()));
while remaining != 0 {
let read = self.read_available()?;
if read == 0 {
break;
}
remaining = remaining.saturating_sub(read);
}
}
let preserved = self.input.preserved_records();
while self.replayed_records < preserved.len() {
let remaining = &preserved[self.replayed_records..];
let mut written = 0;
let result = unsafe {
WriteConsoleInputW(
self.handle,
remaining.as_ptr(),
remaining.len().min(u32::MAX as usize) as u32,
&mut written,
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
if written == 0 {
return Err(io::Error::from(ErrorKind::WriteZero));
}
self.replayed_records += written as usize;
}
self.input.records.clear();
self.input.bytes.clear();
self.input.byte_record_indices.clear();
self.replayed_records = 0;
Ok(())
}
}
impl Drop for ConsoleInputReplay {
fn drop(&mut self) {
if let Err(error) = self.replay() {
tracing::warn!(%error, "failed to restore Windows terminal startup input");
}
}
}
fn write_all(handle: HANDLE, mut bytes: &[u8]) -> io::Result<()> {
while !bytes.is_empty() {
let mut written = 0;
let result = unsafe {
WriteFile(
handle,
bytes.as_ptr().cast(),
bytes.len().min(u32::MAX as usize) as u32,
&mut written,
std::ptr::null_mut(),
)
};
if result == 0 {
return Err(io::Error::last_os_error());
}
if written == 0 {
return Err(io::Error::from(ErrorKind::WriteZero));
}
bytes = &bytes[written as usize..];
}
Ok(())
}
fn query_console_default_colors(output: HANDLE) -> io::Result<Option<DefaultColors>> {
let mut info = unsafe { std::mem::zeroed::<CONSOLE_SCREEN_BUFFER_INFOEX>() };
info.cbSize = std::mem::size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32;
if unsafe { GetConsoleScreenBufferInfoEx(output, &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(Some(decode_console_default_colors(
info.wAttributes,
&info.ColorTable,
)))
}
fn decode_console_default_colors(attributes: u16, color_table: &[u32; 16]) -> DefaultColors {
let fg_index = (attributes & 0x0f) as usize;
let bg_index = ((attributes >> 4) & 0x0f) as usize;
// COMMON_LVB_REVERSE_VIDEO changes how cells render, but this probe is discovering the
// configured default colors for palette blending. Keep the attribute fg/bg indices as-is.
DefaultColors {
fg: decode_color_ref(color_table[fg_index]),
bg: decode_color_ref(color_table[bg_index]),
}
}
fn decode_color_ref(color_ref: u32) -> (u8, u8, u8) {
(
(color_ref & 0xff) as u8,
((color_ref >> 8) & 0xff) as u8,
((color_ref >> 16) & 0xff) as u8,
)
}
fn std_handle(kind: u32) -> io::Result<HANDLE> {
let handle = unsafe { GetStdHandle(kind) };
if handle == 0 || handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(handle)
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod tests;
@@ -0,0 +1,84 @@
//! Identify terminal-color replies without changing unrelated Windows console input.
use std::ops::Range;
const MAX_TERMINAL_COLOR_RESPONSE_BYTES: usize = 1_024;
const PASTE_START: &[u8] = b"\x1b[200~";
const PASTE_END: &[u8] = b"\x1b[201~";
/// Return the byte ranges occupied by complete, valid OSC 10/11 color responses.
///
/// The Windows probe maps these byte ranges back to their original `INPUT_RECORD`s so keyboard
/// modifiers, UTF-16 input, mouse events, and focus changes can be replayed without reconstruction.
pub(super) fn terminal_color_response_ranges(input: &[u8]) -> Vec<Range<usize>> {
let mut ranges = Vec::new();
let mut cursor = 0;
while cursor < input.len() {
if input[cursor..].starts_with(PASTE_START) {
let payload_start = cursor + PASTE_START.len();
let Some(payload_end) = super::find_subslice(&input[payload_start..], PASTE_END) else {
break;
};
cursor = payload_start + payload_end + PASTE_END.len();
continue;
}
if !input[cursor..].starts_with(b"\x1b]") {
cursor += 1;
continue;
}
let start = cursor;
let response = &input[start..];
let Some((slot, prefix)) = [(10_u8, b"\x1b]10;"), (11_u8, b"\x1b]11;")]
.into_iter()
.find(|(_, prefix)| response.starts_with(*prefix))
else {
cursor = start + b"\x1b]".len();
continue;
};
let payload_start = start + prefix.len();
let bounded_end = input
.len()
.min(start.saturating_add(MAX_TERMINAL_COLOR_RESPONSE_BYTES));
let Some((payload_len, terminator_len)) =
super::osc_payload_end(&input[payload_start..bounded_end])
else {
cursor = payload_start;
continue;
};
let end = payload_start + payload_len + terminator_len;
if super::parse_osc_color(&input[start..end], slot).is_some() {
ranges.push(start..end);
}
cursor = end;
}
ranges
}
/// Parse only real probe replies, never OSC-looking content inside a bracketed paste.
pub(super) fn terminal_default_colors(input: &[u8]) -> Option<super::DefaultColors> {
let mut foreground = None;
let mut background = None;
for range in terminal_color_response_ranges(input) {
let response = &input[range];
if foreground.is_none() {
foreground = super::parse_osc_color(response, /*slot*/ 10);
}
if background.is_none() {
background = super::parse_osc_color(response, /*slot*/ 11);
}
}
Some(super::DefaultColors {
fg: foreground?,
bg: background?,
})
}
#[cfg(test)]
#[path = "windows_replay_tests.rs"]
mod tests;
@@ -0,0 +1,94 @@
use super::MAX_TERMINAL_COLOR_RESPONSE_BYTES;
use super::terminal_color_response_ranges;
use super::terminal_default_colors;
use crate::terminal_probe::DefaultColors;
use pretty_assertions::assert_eq;
fn preserved_input(input: &[u8]) -> Vec<u8> {
let ranges = terminal_color_response_ranges(input);
input
.iter()
.enumerate()
.filter_map(|(index, byte)| {
(!ranges.iter().any(|range| range.contains(&index))).then_some(*byte)
})
.collect()
}
#[test]
fn preserves_typeahead_before_between_and_after_terminal_color_replies() {
let input = b"before\x1b]10;rgb:5555/5757/5353\x1b\\between\x1b]11;rgb:ffff/ffff/ffff\x07after";
assert_eq!(preserved_input(input), b"beforebetweenafter");
}
#[test]
fn preserves_unrelated_malformed_and_partial_osc_sequences() {
let input = b"\x1b]52;clipboard\x07\x1b]10;not-a-color\x07typed\x1b]11;rgb:ffff/ffff";
assert_eq!(preserved_input(input), input);
}
#[test]
fn preserves_terminal_color_response_that_exceeds_the_byte_limit() {
let mut input = b"prefix\x1b]10;".to_vec();
input.extend(std::iter::repeat_n(b'x', MAX_TERMINAL_COLOR_RESPONSE_BYTES));
input.extend_from_slice(b"\x07suffix");
assert_eq!(preserved_input(&input), input);
}
#[test]
fn finds_terminal_color_replies_after_unrelated_escape_sequences() {
let input = b"\x1b]52;clipboard\x07typed\x1b]11;rgba:ffff/eeee/dddd/ffff\x1b\\suffix";
assert_eq!(preserved_input(input), b"\x1b]52;clipboard\x07typedsuffix");
}
#[test]
fn consumes_one_and_three_digit_terminal_color_replies() {
let input = b"before\x1b]10;rgb:f/e/d\x07middle\x1b]11;rgb:fff/800/000\x1b\\after";
assert_eq!(preserved_input(input), b"beforemiddleafter");
assert_eq!(
terminal_default_colors(input),
Some(DefaultColors {
fg: (255, 238, 221),
bg: (255, 127, 0),
})
);
}
#[test]
fn preserves_complete_osc_looking_bracketed_paste() {
let input = b"before\x1b[200~\x1b]10;rgb:f/e/d\x07\x1b]11;rgb:fff/800/000\x07\x1b[201~after";
assert_eq!(preserved_input(input), input);
assert_eq!(terminal_default_colors(input), None);
}
#[test]
fn preserves_unfinished_osc_looking_bracketed_paste() {
let input = b"before\x1b[200~\x1b]10;rgb:f/e/d\x07\x1b]11;rgb:fff/800/000\x07";
assert_eq!(preserved_input(input), input);
assert_eq!(terminal_default_colors(input), None);
}
#[test]
fn parses_real_color_replies_around_bracketed_paste() {
let input =
b"\x1b]10;rgb:f/e/d\x07\x1b[200~\x1b]11;rgb:0/0/0\x07\x1b[201~\x1b]11;rgb:fff/800/000\x07";
assert_eq!(
preserved_input(input),
b"\x1b[200~\x1b]11;rgb:0/0/0\x07\x1b[201~"
);
assert_eq!(
terminal_default_colors(input),
Some(DefaultColors {
fg: (255, 238, 221),
bg: (255, 127, 0),
})
);
}
@@ -0,0 +1,206 @@
use super::BufferedConsoleInput;
use super::DefaultColors;
use super::decode_console_default_colors;
use pretty_assertions::assert_eq;
use windows_sys::Win32::System::Console::COMMON_LVB_REVERSE_VIDEO;
use windows_sys::Win32::System::Console::FOCUS_EVENT;
use windows_sys::Win32::System::Console::FOCUS_EVENT_RECORD;
use windows_sys::Win32::System::Console::INPUT_RECORD;
use windows_sys::Win32::System::Console::INPUT_RECORD_0;
use windows_sys::Win32::System::Console::KEY_EVENT;
use windows_sys::Win32::System::Console::KEY_EVENT_RECORD;
use windows_sys::Win32::System::Console::KEY_EVENT_RECORD_0;
fn color_table() -> [u32; 16] {
[
0x00000000, 0x00000080, 0x00008000, 0x00008080, 0x00800000, 0x00800080, 0x00808000,
0x00c0c0c0, 0x00808080, 0x000000ff, 0x0000ff00, 0x0000ffff, 0x00ff0000, 0x00ff00ff,
0x00ffff00, 0x00ffffff,
]
}
fn key_record(character: u16, pressed: bool, control_key_state: u32) -> INPUT_RECORD {
INPUT_RECORD {
EventType: KEY_EVENT as u16,
Event: INPUT_RECORD_0 {
KeyEvent: KEY_EVENT_RECORD {
bKeyDown: i32::from(pressed),
wRepeatCount: 1,
wVirtualKeyCode: character,
wVirtualScanCode: 0,
uChar: KEY_EVENT_RECORD_0 {
UnicodeChar: character,
},
dwControlKeyState: control_key_state,
},
},
}
}
fn push_ascii(input: &mut BufferedConsoleInput, bytes: &[u8]) {
for byte in bytes {
input.push(key_record(
u16::from(*byte),
/*pressed*/ true,
/*control_key_state*/ 0,
));
}
}
#[test]
fn preserves_typeahead_records_and_modifier_state_around_color_responses() {
let mut input = BufferedConsoleInput::default();
let before = key_record(
u16::from(b'a'),
/*pressed*/ true,
/*control_key_state*/ 8,
);
let after = key_record(
u16::from(b'b'),
/*pressed*/ true,
/*control_key_state*/ 16,
);
input.push(before);
push_ascii(&mut input, b"\x1b]10;rgb:5555/5757/5353\x1b\\");
input.push(after);
push_ascii(&mut input, b"\x1b]11;rgb:ffff/ffff/ffff\x07");
let preserved = input.preserved_records();
assert_eq!(preserved.len(), 2);
// SAFETY: Both preserved records are constructed as KEY_EVENT records above.
let states: Vec<_> = preserved
.iter()
.map(|record| unsafe { record.Event.KeyEvent.dwControlKeyState })
.collect();
assert_eq!(states, vec![8, 16]);
}
#[test]
fn preserves_focus_unicode_and_key_release_console_records() {
let mut input = BufferedConsoleInput::default();
let focus = INPUT_RECORD {
EventType: FOCUS_EVENT as u16,
Event: INPUT_RECORD_0 {
FocusEvent: FOCUS_EVENT_RECORD { bSetFocus: 1 },
},
};
let unicode = key_record(
/*character*/ 0x00e9, /*pressed*/ true, /*control_key_state*/ 0,
);
let release = key_record(
u16::from(b'x'),
/*pressed*/ false,
/*control_key_state*/ 2,
);
input.push(focus);
push_ascii(&mut input, b"\x1b]10;rgb:5555/5757/5353\x1b\\");
input.push(unicode);
input.push(release);
push_ascii(&mut input, b"\x1b]11;rgb:ffff/ffff/ffff\x07");
let preserved = input.preserved_records();
assert_eq!(preserved.len(), 3);
assert_eq!(preserved[0].EventType, FOCUS_EVENT as u16);
// SAFETY: The final records were constructed as KEY_EVENT records above.
let unicode_character = unsafe { preserved[1].Event.KeyEvent.uChar.UnicodeChar };
let release_pressed = unsafe { preserved[2].Event.KeyEvent.bKeyDown };
assert_eq!(unicode_character, 0x00e9);
assert_eq!(release_pressed, 0);
}
#[test]
fn preserves_fifo_order_when_later_console_records_are_buffered() {
let mut input = BufferedConsoleInput::default();
input.push(key_record(
u16::from(b'a'),
/*pressed*/ true,
/*control_key_state*/ 8,
));
push_ascii(&mut input, b"\x1b]10;rgb:5/5/5\x07");
push_ascii(&mut input, b"\x1b]11;rgb:f/f/f\x07");
// replay() drains records that arrived after its last probe read before writing anything.
input.push(key_record(
u16::from(b'b'),
/*pressed*/ true,
/*control_key_state*/ 16,
));
let preserved = input.preserved_records();
let characters: Vec<_> = preserved
.iter()
// SAFETY: Both surviving records are KEY_EVENT values constructed above.
.map(|record| unsafe { record.Event.KeyEvent.uChar.UnicodeChar })
.collect();
assert_eq!(characters, vec![u16::from(b'a'), u16::from(b'b')]);
}
#[test]
fn preserves_osc_looking_bracketed_paste_records() {
let mut input = BufferedConsoleInput::default();
push_ascii(
&mut input,
b"\x1b[200~\x1b]10;rgb:f/e/d\x07\x1b]11;rgb:0/0/0\x07\x1b[201~",
);
assert_eq!(input.preserved_records().len(), input.records.len());
}
#[test]
fn preserves_every_record_when_no_valid_color_response_arrives() {
let mut input = BufferedConsoleInput::default();
push_ascii(&mut input, b"typed\x1b]10;incomplete");
assert_eq!(input.preserved_records().len(), input.records.len());
}
#[test]
fn decodes_console_color_attribute_indices() {
assert_eq!(
decode_console_default_colors(/*attributes*/ 0x21, &color_table()),
DefaultColors {
fg: (128, 0, 0),
bg: (0, 128, 0),
}
);
}
#[test]
fn decodes_console_color_intensity_indices() {
assert_eq!(
decode_console_default_colors(/*attributes*/ 0xe9, &color_table()),
DefaultColors {
fg: (255, 0, 0),
bg: (0, 255, 255),
}
);
}
#[test]
fn decodes_console_color_ref_byte_order() {
let mut colors = color_table();
colors[3] = 0x00112233;
colors[4] = 0x00aabbcc;
assert_eq!(
decode_console_default_colors(/*attributes*/ 0x43, &colors),
DefaultColors {
fg: (0x33, 0x22, 0x11),
bg: (0xcc, 0xbb, 0xaa),
}
);
}
#[test]
fn ignores_reverse_video_when_decoding_default_colors() {
assert_eq!(
decode_console_default_colors(
/*attributes*/ COMMON_LVB_REVERSE_VIDEO | 0x21,
&color_table(),
),
DefaultColors {
fg: (128, 0, 0),
bg: (0, 128, 0),
}
);
}