Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add an unmasked-last-char display mode for passwords #281

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Fix autocomplete suggestions not being updated after a suggestion is accepted. Thanks @moritz-hoelting and @istudyatuni for reporting and fixing it!
- Fix incorrect cursor placement when inputting CJK characters. Thanks @phostann (#270) for reporting it!
- Removed unused dependency (newline-converter). Thanks @jonassmedegaard (#267) for catching it!
- Add a new password display mode to mask all but the last character. Thanks @nico-incubiq (#281) for the PR.

## [0.7.5] - 2024-04-23

Expand Down
10 changes: 10 additions & 0 deletions KEY_BINDINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ These key bindings may be used in [`Editor`] prompts.
| <kbd>enter</kbd> | Submit the current content of the temporary file being edited. |


## Password Prompts

These key bindings may be used in [`Password`] prompts.

| **command** | **description** |
|--------------------------------|----------------------------------------------------------------------------------------|
| <kbd>ctrl</kbd> + <kbd>r</kbd> | Toggles between [`Masked`]/[`UnmaskedLastChar`] and [`Full`] (unmasked) display modes. |


[`Text`]: https://docs.rs/inquire/*/inquire/prompts/text/struct.Text.html
Expand All @@ -126,3 +133,6 @@ These key bindings may be used in [`Editor`] prompts.
[`Editor`]: https://docs.rs/inquire/*/inquire/prompts/editor/struct.Editor.html
[`customtype`]: https://docs.rs/inquire/*/inquire/struct.CustomType.html
[`Password`]: https://docs.rs/inquire/*/inquire/prompts/password/struct.Password.html
[`Masked`]: https://docs.rs/inquire/latest/inquire/enum.PasswordDisplayMode.html#variant.Masked
[`UnmaskedLastChar`]: https://docs.rs/inquire/latest/inquire/enum.PasswordDisplayMode.html#variant.UnmaskedLastChar
[`Full`]: https://docs.rs/inquire/latest/inquire/enum.PasswordDisplayMode.html#variant.Full
13 changes: 13 additions & 0 deletions inquire/examples/password_unmasked_last_char.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use inquire::{Password, PasswordDisplayMode};

fn main() {
let name = Password::new("RSA Encryption Key:")
.with_display_toggle_enabled()
.with_display_mode(PasswordDisplayMode::UnmaskedLastChar)
.prompt();

match name {
Ok(_) => println!("This doesn't look like a key."),
Err(_) => println!("An error happened when asking for your key, try again later."),
}
}
4 changes: 4 additions & 0 deletions inquire/src/prompts/password/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ pub enum PasswordDisplayMode {
/// render config.
Masked,

/// Same as [Masked](PasswordDisplayMode::Masked), but the last typed
/// character remains unmasked immediately after typing it.
UnmaskedLastChar,

/// Password text input is fully rendered as a normal input, just like
/// [Text](crate::Text) prompts.
Full,
Expand Down
36 changes: 34 additions & 2 deletions inquire/src/prompts/password/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
prompts::prompt::{ActionResult, Prompt},
ui::PasswordBackend,
validator::{ErrorMessage, StringValidator, Validation},
InquireError, Password, PasswordDisplayMode,
InputAction, InquireError, Password, PasswordDisplayMode,
};

use super::{action::PasswordPromptAction, config::PasswordConfig};
Expand Down Expand Up @@ -33,6 +33,7 @@ pub struct PasswordPrompt<'a> {
formatter: StringFormatter<'a>,
validators: Vec<Box<dyn StringValidator>>,
error: Option<ErrorMessage>,
appending_chars: bool,
}

impl<'a> From<Password<'a>> for PasswordPrompt<'a> {
Expand All @@ -59,6 +60,7 @@ impl<'a> From<Password<'a>> for PasswordPrompt<'a> {
validators: so.validators,
input: Input::new(),
error: None,
appending_chars: false,
}
}
}
Expand All @@ -82,7 +84,9 @@ impl<'a> PasswordPrompt<'a> {

fn toggle_display_mode(&mut self) -> ActionResult {
let new_mode = match self.current_mode {
PasswordDisplayMode::Hidden | PasswordDisplayMode::Masked => PasswordDisplayMode::Full,
PasswordDisplayMode::Hidden
| PasswordDisplayMode::Masked
| PasswordDisplayMode::UnmaskedLastChar => PasswordDisplayMode::Full,
PasswordDisplayMode::Full => self.config.display_mode,
};

Expand Down Expand Up @@ -196,8 +200,12 @@ where
}

fn handle(&mut self, action: PasswordPromptAction) -> InquireResult<ActionResult> {
self.appending_chars = false;
let result = match action {
PasswordPromptAction::ValueInput(input_action) => {
if let InputAction::Write(_) = input_action {
self.appending_chars = true;
}
self.active_input_mut().handle(input_action).into()
}
PasswordPromptAction::ToggleDisplayMode => self.toggle_display_mode(),
Expand Down Expand Up @@ -235,6 +243,30 @@ where
_ => {}
}
}
PasswordDisplayMode::UnmaskedLastChar => {
if !self.confirmation_stage && self.appending_chars {
backend
.render_prompt_with_unmasked_last_char_input(self.message, &self.input)?;
} else {
backend.render_prompt_with_masked_input(self.message, &self.input)?;
}

if self.confirmation_stage {
if let Some(confirmation) = &self.confirmation {
if self.appending_chars {
backend.render_prompt_with_unmasked_last_char_input(
confirmation.message,
&confirmation.input,
)?;
} else {
backend.render_prompt_with_masked_input(
confirmation.message,
&confirmation.input,
)?;
}
}
}
}
PasswordDisplayMode::Full => {
backend.render_prompt_with_full_input(self.message, &self.input)?;

Expand Down
3 changes: 2 additions & 1 deletion inquire/src/ui/api/render_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ pub struct RenderConfig<'a> {
pub help_message: StyleSheet,

/// Character used to mask password text inputs when in mode
/// [`Masked`](crate::prompts::PasswordDisplayMode).
/// [`Masked`](crate::prompts::PasswordDisplayMode::Masked) or
/// [`UnmaskedLastChar`](crate::prompts::PasswordDisplayMode::UnmaskedLastChar).
///
/// Note: Styles for masked text inputs are set in the
/// [`text_input`](crate::ui::RenderConfig::text_input) configuration.
Expand Down
20 changes: 20 additions & 0 deletions inquire/src/ui/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ pub trait CustomTypeBackend: CommonBackend {
pub trait PasswordBackend: CommonBackend {
fn render_prompt(&mut self, prompt: &str) -> Result<()>;
fn render_prompt_with_masked_input(&mut self, prompt: &str, cur_input: &Input) -> Result<()>;
fn render_prompt_with_unmasked_last_char_input(
&mut self,
prompt: &str,
cur_input: &Input,
) -> Result<()>;
fn render_prompt_with_full_input(&mut self, prompt: &str, cur_input: &Input) -> Result<()>;
}

Expand Down Expand Up @@ -647,6 +652,21 @@ where
self.print_prompt_with_input(prompt, None, &masked_input)
}

fn render_prompt_with_unmasked_last_char_input(
&mut self,
prompt: &str,
cur_input: &Input,
) -> Result<()> {
let masked_string: String = (0..cur_input.length().saturating_sub(1))
.map(|_| self.render_config.password_mask)
.chain(cur_input.content().chars().rev().take(1))
.collect();

let masked_input = Input::new_with(masked_string).with_cursor(cur_input.cursor());

self.print_prompt_with_input(prompt, None, &masked_input)
}

fn render_prompt_with_full_input(&mut self, prompt: &str, cur_input: &Input) -> Result<()> {
self.print_prompt_with_input(prompt, None, cur_input)
}
Expand Down
Loading