mnemo_engine/keys/
display.rs1use std::io::{IsTerminal, Write};
11
12pub const AGENT_MARKERS: &[&str] = &["CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION"];
30
31pub const REFUSAL: &str = "the recovery code wasn't shown, because this doesn't look like a \
33terminal a person is at. Run `mnemo recovery-code <file>` in a terminal of your own, not \
34through an agent's shell or an editor terminal that one runs in (for example, Claude Code's `!`)";
35
36pub fn refusal_reason() -> Option<String> {
38 if !std::io::stdout().is_terminal() {
39 return Some("stdout isn't a terminal".into());
40 }
41 if !std::io::stdin().is_terminal() {
42 return Some("stdin isn't a terminal".into());
43 }
44 marker_reason(|k| std::env::var_os(k))
45 .or_else(|| (!controlling_terminal_opens()).then(|| "no controlling terminal".into()))
46}
47
48pub fn marker_reason(get: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<String> {
50 AGENT_MARKERS
51 .iter()
52 .find(|m| get(m).is_some_and(|v| !v.is_empty()))
53 .map(|m| format!("{m} is set (an agent harness)"))
54}
55
56#[cfg(unix)]
57fn controlling_terminal_opens() -> bool {
58 std::fs::OpenOptions::new()
59 .read(true)
60 .write(true)
61 .open("/dev/tty")
62 .is_ok()
63}
64
65#[cfg(windows)]
66fn controlling_terminal_opens() -> bool {
67 std::fs::OpenOptions::new()
68 .read(true)
69 .write(true)
70 .open("CONOUT$")
71 .is_ok()
72}
73
74#[cfg(not(any(unix, windows)))]
75fn controlling_terminal_opens() -> bool {
76 false
77}
78
79pub fn show(code: &str) -> std::io::Result<()> {
83 rpassword::prompt_password(
84 "Press Enter to show the recovery code. Make sure this is your own terminal. ",
85 )?;
86 let mut tty = open_tty()?;
87 #[cfg(unix)]
88 write!(tty, "\x1b[?1049h\x1b[H\x1b[2J")?;
89 write!(
90 tty,
91 "Your recovery code:\r\n\r\n {code}\r\n\r\n\
92 Write it down and keep it somewhere safe. It's the only way to open this brain \r\n\
93 on another machine, or here if the keychain entry is lost.\r\n\r\n"
94 )?;
95 #[cfg(not(unix))]
96 write!(
97 tty,
98 "Clear the screen (cls) once you've written it down.\r\n\r\n"
99 )?;
100 tty.flush()?;
101 drop(tty);
102 let r = rpassword::prompt_password("Press Enter when you've written it down. ");
103 let mut tty = open_tty()?;
104 #[cfg(unix)]
105 write!(tty, "\x1b[?1049l")?;
106 tty.flush()?;
107 r.map(|_| ())
108}
109
110pub fn ask_hidden(prompt: &str) -> std::io::Result<String> {
113 rpassword::prompt_password(prompt)
114}
115
116#[cfg(unix)]
117fn open_tty() -> std::io::Result<std::fs::File> {
118 std::fs::OpenOptions::new().write(true).open("/dev/tty")
119}
120
121#[cfg(windows)]
122fn open_tty() -> std::io::Result<std::fs::File> {
123 std::fs::OpenOptions::new().write(true).open("CONOUT$")
124}
125
126#[cfg(not(any(unix, windows)))]
127fn open_tty() -> std::io::Result<std::fs::File> {
128 Err(std::io::Error::new(
129 std::io::ErrorKind::Unsupported,
130 "no controlling terminal",
131 ))
132}