Skip to main content

mnemo_engine/keys/
display.rs

1//! 12.3: the display rule (the keys note, section 7). A recovery code is
2//! shown only to a person at a terminal: stdout and stdin are terminals, no
3//! known agent-harness marker is set, and the controlling terminal opens.
4//! It's shown through the controlling terminal, after a key press, on the
5//! alternate screen, so nothing reaches stdout or stays in scrollback. On
6//! Windows there's no alternate screen (the escapes are Unix-only), so the
7//! code stays in the console's scrollback; `init --help` and the CHANGELOG
8//! say so.
9
10use std::io::{IsTerminal, Write};
11
12/// Environment variables that agent harnesses set in the commands they
13/// run. Each is checked against its vendor's documentation, cited here. A
14/// marker only makes the rule stricter; only whether it's set (and not
15/// empty) is read. **A best effort**: it can only name harnesses someone
16/// has checked, so the key press is the guard that doesn't depend on it.
17///
18/// - `CLAUDECODE`: "Set to `1` in subprocesses Claude Code spawns (Bash
19///   and PowerShell tools, tmux sessions, hook commands, status line
20///   commands, stdio MCP server subprocesses). IDE extensions also set this
21///   in their integrated terminals."
22///   <https://code.claude.com/docs/en/env-vars>
23/// - `CLAUDE_CODE_CHILD_SESSION`: "Set to `1` in subprocesses Claude Code
24///   spawns via the Bash, PowerShell, and Monitor tools, hook commands, and
25///   status line commands." Same page.
26///
27/// A candidate not yet on the list: `AI_AGENT`, a proposed cross-tool
28/// convention; no vendor's documentation found yet.
29pub const AGENT_MARKERS: &[&str] = &["CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION"];
30
31/// What the user is told when a code isn't shown.
32pub 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
36/// Why the rule doesn't hold here, or `None` when it does.
37pub 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
48/// The marker part of the rule, over an environment lookup (for tests).
49pub 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
79/// Show `code` under the rule: ask for Enter first, then show it on the
80/// alternate screen, wait for Enter again, and leave it. Call only when
81/// [`refusal_reason`] is `None`. The answers are read without echo.
82pub 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
110/// Ask on the controlling terminal for `prompt` and read the answer
111/// without echo (`onboard`'s confirmation of the last group).
112pub 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}