vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! The login screen (the session entry point).
//!
//! A display-manager-style login: the OS banner, the account name, and a
//! password box. Like real GUI logins (Windows logon, macOS, desktop
//! greeters), a failed attempt reveals the account's password hint — which
//! is per-account state (`UnixUser::hint`), not interface chrome. On a
//! default install the hint is the account's own name, matching the default
//! password convention; scenarios set whatever hint they like.
//!
//! Every attempt — successful or not — is recorded through
//! [`os::unix::login_records`], so `who` and `last` observe the session
//! history exactly as on a real machine.

use std::io::Write as _;

use crossterm::event::{self, Event};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};

use os::Credentials;
use os::unix::unix_os::UnixOs;

/// The inner width of the password box on a full-size terminal.
const BOX_WIDTH: usize = 32;

/// The placeholder in an empty box; it yields on the first keystroke.
const PLACEHOLDER: &str = "enter password here";

/// The terminal columns used when the real size is unavailable (tests,
/// pipes): wide enough for the full layout.
const FALLBACK_COLUMNS: usize = 80;

/// The smallest terminal the layout stays coherent in.
const MINIMUM_COLUMNS: usize = 20;

/// How many columns text occupies on screen: escape sequences style the
/// text, they do not occupy it.
fn visible(text: &str) -> usize {
    let mut count = 0;
    let mut rest = text;
    while let Some(start) = rest.find('\x1b') {
        count += rest[..start].chars().count();
        // Skip the introducer through its terminating letter.
        match rest[start..].find(|ch: char| ch.is_ascii_alphabetic()) {
            Some(end) => rest = &rest[start + end + 1..],
            None => break,
        }
    }
    count + rest.chars().count()
}

/// One rendered login screen. Separate from the event loop so tests can
/// assert on frames without driving keys.
struct LoginScreen {
    os_name: String,
    #[allow(dead_code)]
    host: String,
    user: String,
    input: String,
    failure: Option<String>,
    /// The account's hint, revealed only after a failed attempt.
    hint: Option<String>,
}

impl LoginScreen {
    fn new(os_name: &str, host: &str, user: &str) -> Self {
        Self {
            os_name: os_name.to_owned(),
            host: host.to_owned(),
            user: user.to_owned(),
            input: String::new(),
            failure: None,
            hint: None,
        }
    }

    /// Draws one frame for a terminal `columns` wide. Every emitted line
    /// fits: the password box shrinks before anything wraps.
    fn frame_with_width(&self, columns: usize) -> String {
        let columns = columns.max(MINIMUM_COLUMNS);
        let center = |text: &str| {
            let pad = columns.saturating_sub(visible(text)) / 2;
            format!("{}{text}\x1b[K", " ".repeat(pad))
        };

        let mut f = String::new();
        f.push_str("\x1b[H");

        // Banner: a boxed reverse-video title; when the terminal is too
        // narrow for even that, the bare title stands alone.
        let title = self.os_name.to_uppercase();
        let title_width = title.chars().count();
        if title_width + 10 <= columns {
            let rule = "═".repeat(title_width + 6);
            // Padded to exactly the rule's run, so ╔/║/╚ share one width.
            let padded = format!("{title:^width$}", width = title_width + 6);
            f.push_str(&center(&format!("╔{rule}╗")));
            f.push_str("\r\n");
            f.push_str(&center(&format!("║\x1b[7m{padded}\x1b[0m║")));
            f.push_str("\r\n");
            f.push_str(&center(&format!("╚{rule}╝")));
        } else {
            f.push_str(&center(&format!("\x1b[7m{title}\x1b[0m")));
        }
        f.push_str("\r\n");
        f.push_str("\x1b[K\r\n");

        // Username centered on its own line (no "login:" label).
        f.push_str(&center(&self.user));
        f.push_str("\r\n\x1b[K\r\n");

        // The password box narrows with the terminal; the placeholder only
        // appears when it fits inside.
        let box_inner = BOX_WIDTH.min(columns.saturating_sub(8)).max(6);
        let inner = if self.input.is_empty() {
            if PLACEHOLDER.len() <= box_inner {
                format!(
                    "\x1b[2m{PLACEHOLDER}\x1b[0m{}",
                    " ".repeat(box_inner - PLACEHOLDER.len())
                )
            } else {
                " ".repeat(box_inner)
            }
        } else {
            let dots: String = self.input.chars().take(box_inner).map(|_| '•').collect();
            format!("{dots}{}", " ".repeat(box_inner - dots.chars().count()))
        };
        let edge = "─".repeat(box_inner + 2);
        f.push_str(&center(&format!("┌{edge}┐")));
        f.push_str("\r\n");
        f.push_str(&center(&format!("│ {inner} │")));
        f.push_str("\r\n");
        f.push_str(&center(&format!("└{edge}┘")));
        f.push_str("\r\n");

        if let Some(message) = &self.failure {
            // Failure text is quiet: dim, one line each, hint last.
            f.push_str("\r\n");
            f.push_str(&center(&format!("\x1b[2m{message}\x1b[0m")));
            f.push_str("\r\n");
            if let Some(hint) = &self.hint {
                // Long hints wrap on words; no line ever leaves the width.
                let prefix = "Hint: ";
                let mut line = String::new();
                for word in hint.split_whitespace() {
                    let candidate = if line.is_empty() {
                        format!("{prefix}{word}")
                    } else {
                        format!("{line} {word}")
                    };
                    if visible(&candidate) > columns && !line.is_empty() {
                        f.push_str(&center(&format!("\x1b[2m{line}\x1b[0m")));
                        f.push_str("\r\n");
                        line = format!("{prefix}{word}");
                    } else {
                        line = candidate;
                    }
                }
                if !line.is_empty() {
                    f.push_str(&center(&format!("\x1b[2m{line}\x1b[0m")));
                    f.push_str("\r\n");
                }
            }
        }
        f
    }

    fn cursor_position(&self, columns: usize) -> (u16, u16) {
        let columns = columns.max(MINIMUM_COLUMNS);
        let title_width = self.os_name.to_uppercase().chars().count();
        let banner_rows: u16 = if title_width + 10 <= columns { 3 } else { 1 };
        // banner (3 or 1) + blank + username + blank + box top
        let row: u16 = banner_rows + 1 + 1 + 1 + 2;
        let box_inner = BOX_WIDTH.min(columns.saturating_sub(8)).max(6) as u16;
        let box_width = box_inner + 4;
        let pad = (columns as u16).saturating_sub(box_width) / 2;
        let col: u16 = pad + 3 + (self.input.chars().count() as u16).min(box_inner);
        (row, col)
    }

    /// Draws one frame at the terminal's real size.
    #[allow(dead_code)]
    fn frame(&self) -> String {
        let columns = crossterm::terminal::size()
            .map(|(cols, _)| usize::from(cols))
            .unwrap_or(FALLBACK_COLUMNS);
        self.frame_with_width(columns)
    }
}

/// Runs the login screen until authentication succeeds or the user aborts
/// with Ctrl+C/Ctrl+D. Every attempt is recorded to wtmp/btmp. Returns the
/// credentials on success; `None` means the user gave up.
pub fn run(
    unix: &UnixOs,
    display_name: &str,
    host: &str,
    user: &str,
) -> Result<Credentials, String> {
    let mut state = LoginScreen::new(display_name, host, user);
    state.hint = unix
        .users()
        .by_name(user)
        .and_then(|account| account.hint().map(str::to_owned));

    let _raw = enable_raw_mode();
    let _ = crossterm::execute!(std::io::stdout(), EnterAlternateScreen);
    // Hide cursor during redraw, show inside box after
    let mut columns = crossterm::terminal::size()
        .map(|(c, _)| usize::from(c))
        .unwrap_or(FALLBACK_COLUMNS);
    let mut frame = state.frame_with_width(columns);
    print!("{frame}");
    let (row, col) = state.cursor_position(columns);
    print!("\x1b[{row};{col}H\x1b[?25h");
    let _ = std::io::stdout().flush();

    // The event stream carries more than keys — resizes, focus changes,
    // paste notifications. Only a key can end the session; everything else
    // falls through to a redraw (the layout reads the live width, so a
    // resize simply re-renders at the new size).
    loop {
        match event::read() {
            Ok(Event::Key(key)) => match crate::host::translate_key(&key) {
                Some(engine::KeyEvent {
                    key: engine::Key::Character,
                    character: Some('c' | 'd'),
                    ctrl: true,
                    ..
                }) => break,
                Some(engine::KeyEvent {
                    key: engine::Key::Character,
                    character: Some(ch),
                    ctrl: false,
                    ..
                }) => {
                    state.input.push(ch);
                    state.failure = None;
                }
                Some(engine::KeyEvent {
                    key: engine::Key::Backspace,
                    ..
                }) => {
                    state.input.pop();
                }
                Some(engine::KeyEvent {
                    key: engine::Key::Enter,
                    ..
                }) => {
                    let attempt = std::mem::take(&mut state.input);
                    match unix.users().authenticate(user, &attempt, unix.groups()) {
                        Ok(credentials) => {
                            unix.record_login_attempt(user, true);
                            let _ = crossterm::execute!(std::io::stdout(), LeaveAlternateScreen);
                            let _ = disable_raw_mode();
                            return Ok(credentials);
                        }
                        Err(_) => {
                            unix.record_login_attempt(user, false);
                            // The hint renders once, below the message, from
                            // its own field.
                            state.failure = Some("Login incorrect".to_owned());
                        }
                    }
                }
                _ => {}
            },
            Ok(_) => {}
            Err(_) => break,
        }
        // Only redraw on state change or resize; hide cursor during draw
        print!("\x1b[?25l");
        columns = crossterm::terminal::size()
            .map(|(c, _)| usize::from(c))
            .unwrap_or(FALLBACK_COLUMNS);
        frame = state.frame_with_width(columns);
        print!("{frame}");
        let (row, col) = state.cursor_position(columns);
        print!("\x1b[{row};{col}H\x1b[?25h");
        let _ = std::io::stdout().flush();
    }
    let _ = crossterm::execute!(std::io::stdout(), LeaveAlternateScreen);
    let _ = disable_raw_mode();
    Err("login cancelled".to_owned())
}

/// Windows variant of the login screen (same chrome, Windows account store).
pub fn run_windows(
    windows: &os::windows::Windows,
    display_name: &str,
    host: &str,
    user: &str,
) -> Result<engine::ActorId, String> {
    let mut state = LoginScreen::new(display_name, host, user);
    state.hint = windows
        .users()
        .by_name(user)
        .and_then(|account| account.hint().map(str::to_owned));

    let _raw = enable_raw_mode();
    let _ = crossterm::execute!(std::io::stdout(), EnterAlternateScreen);
    let mut columns = crossterm::terminal::size()
        .map(|(c, _)| usize::from(c))
        .unwrap_or(FALLBACK_COLUMNS);
    let mut frame = state.frame_with_width(columns);
    print!("{frame}");
    let (row, col) = state.cursor_position(columns);
    print!("\x1b[{row};{col}H\x1b[?25h");
    let _ = std::io::stdout().flush();

    loop {
        match event::read() {
            Ok(Event::Key(key)) => match crate::host::translate_key(&key) {
                Some(engine::KeyEvent {
                    key: engine::Key::Character,
                    character: Some('c' | 'd'),
                    ctrl: true,
                    ..
                }) => break,
                Some(engine::KeyEvent {
                    key: engine::Key::Character,
                    character: Some(ch),
                    ctrl: false,
                    ..
                }) => {
                    state.input.push(ch);
                    state.failure = None;
                }
                Some(engine::KeyEvent {
                    key: engine::Key::Backspace,
                    ..
                }) => {
                    state.input.pop();
                }
                Some(engine::KeyEvent {
                    key: engine::Key::Enter,
                    ..
                }) => {
                    let attempt = std::mem::take(&mut state.input);
                    // Windows: empty password means no prompt (fresh install), but
                    // the screen always prompts — treat empty as attempt.
                    match windows.authenticate(user, &attempt) {
                        Ok(actor) => {
                            let _ = crossterm::execute!(std::io::stdout(), LeaveAlternateScreen);
                            let _ = disable_raw_mode();
                            return Ok(actor);
                        }
                        Err(_) => {
                            state.failure = Some("Login incorrect".to_owned());
                        }
                    }
                }
                _ => {}
            },
            Ok(_) => {}
            Err(_) => break,
        }
        print!("\x1b[?25l");
        columns = crossterm::terminal::size()
            .map(|(c, _)| usize::from(c))
            .unwrap_or(FALLBACK_COLUMNS);
        frame = state.frame_with_width(columns);
        print!("{frame}");
        let (row, col) = state.cursor_position(columns);
        print!("\x1b[{row};{col}H\x1b[?25h");
        let _ = std::io::stdout().flush();
    }
    let _ = crossterm::execute!(std::io::stdout(), LeaveAlternateScreen);
    let _ = disable_raw_mode();
    Err("login cancelled".to_owned())
}

#[cfg(test)]
mod tests {
    use super::{LoginScreen, PLACEHOLDER, visible};

    fn screen_with_failure() -> LoginScreen {
        let mut state = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo");
        state.input.push('x');
        state.failure = Some("Login incorrect".to_owned());
        state.hint = Some("demo".to_owned());
        state
    }

    #[test]
    fn empty_box_shows_the_placeholder() {
        let frame = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo").frame();
        assert!(
            frame.contains(PLACEHOLDER),
            "empty box invites typing: {frame}"
        );
        assert!(frame.contains("UBUNTU 24.04 LTS"), "banner names the OS");
        assert!(frame.contains("demo"), "prompt shows user");
        assert!(
            !frame.contains("login:"),
            "prompt no longer shows login label"
        );
        assert!(!frame.contains("•"), "nothing typed yet");
    }

    #[test]
    fn typed_characters_render_as_dots_and_dismiss_the_placeholder() {
        let mut state = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo");
        state.input.push_str("abc");
        let frame = state.frame();
        assert!(frame.contains("•••"));
        assert!(!frame.contains(PLACEHOLDER));
    }

    /// At any width, no emitted line may exceed it: split panes must not
    /// wrap the screen into garbage.
    fn assert_lines_fit(frame: &str, columns: usize) {
        for line in frame.split("\r\n") {
            let width = visible(line);
            assert!(
                width <= columns,
                "line of {width} columns overflows a {columns}-column terminal: {line:?}"
            );
        }
    }

    #[test]
    fn frames_fit_narrow_terminals() {
        for columns in [20usize, 30, 40, 50, 60, 80, 120] {
            let mut state = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo");
            state.input.push_str("secret");
            state.failure = Some("Login incorrect".to_owned());
            state.hint = Some("demo".to_owned());
            assert_lines_fit(&state.frame_with_width(columns), columns);
        }
    }

    #[test]
    fn banner_stays_aligned_with_its_own_rules() {
        // The three banner lines share one left edge: escape sequences
        // style text but occupy nothing, so centering must agree.
        let frame = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo").frame();
        let lines: Vec<&str> = frame.split("\r\n").collect();
        let top = visible(lines[0]) - visible("╔");
        let middle = visible(lines[1]) - visible("║");
        let bottom = visible(lines[2]) - visible("╚");
        assert_eq!(top, middle, "banner edges misaligned: {frame:?}");
        assert_eq!(middle, bottom);
    }

    #[test]
    fn narrow_box_drops_the_placeholder_instead_of_wrapping() {
        // At 24 columns the box is 16 inside; the 19-column placeholder
        // yields to an empty box rather than wrapping.
        let frame = LoginScreen::new("Ubuntu 24.04 LTS", "demo-host", "demo").frame_with_width(24);
        assert!(
            !frame.contains(PLACEHOLDER),
            "placeholder wider than the box would wrap"
        );
    }

    #[test]
    fn failure_reveals_the_hint_below_the_box() {
        let frame = screen_with_failure().frame();
        assert!(frame.contains("Login incorrect"));
        assert!(frame.contains("Hint: demo"));
        // The dots are still there: the failed attempt did not erase input.
        assert!(frame.contains("•"));
    }
}