use std::fmt;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use rho_protocol::{SecretAsk, SecretDestination, SecretValue};
use tokio::sync::oneshot;
use zeroize::Zeroize;
use super::{
composer_chrome,
line_editor::LineEditor,
line_editor_view::EditorPresentation,
masked_input::{apply_masked_key, MaskedKey},
panel_text::indented_wrapped_lines,
styled_line, truncate_one_line,
view_composer::{editor_frame, ComposerFrame},
App, ComposerMode, LineFill, Theme, UserWait,
};
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SecretReply {
Save(SecretValue),
Decline,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SecretKey {
Kept,
Reply(SecretReply),
Dismiss,
}
pub(super) struct SecretAskComposer {
ask: SecretAsk,
pub(super) editor: LineEditor,
blank_refused: bool,
reply: Option<oneshot::Sender<SecretReply>>,
restore_side: bool,
}
impl SecretAskComposer {
fn new(ask: SecretAsk, reply: oneshot::Sender<SecretReply>, restore_side: bool) -> Self {
Self {
ask,
editor: LineEditor::new(""),
blank_refused: false,
reply: Some(reply),
restore_side,
}
}
fn asking(&self) -> bool {
self.reply.is_some()
}
fn apply_key(&mut self, key: KeyEvent) -> SecretKey {
if !self.asking() {
return match key.code {
KeyCode::Enter | KeyCode::Esc => SecretKey::Dismiss,
_ => SecretKey::Kept,
};
}
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
return SecretKey::Reply(SecretReply::Decline);
}
match apply_masked_key(&mut self.editor, key) {
MaskedKey::Handled => {
self.blank_refused &= self.editor.value.is_empty();
SecretKey::Kept
}
MaskedKey::Submit => {
let reply = typed_reply(&self.editor.value);
self.blank_refused = reply.is_none();
reply.map_or(SecretKey::Kept, SecretKey::Reply)
}
MaskedKey::Cancel => SecretKey::Reply(SecretReply::Decline),
}
}
pub(super) fn insert_text(&mut self, text: &str) {
if self.asking() {
self.editor.insert_text(text);
}
}
fn respond(&mut self, reply: SecretReply) {
self.editor.value.zeroize();
if let Some(sender) = self.reply.take() {
let _ = sender.send(reply);
}
}
fn close(&mut self) {
self.editor.value.zeroize();
self.editor = LineEditor::new("");
self.blank_refused = false;
self.reply = None;
}
}
impl Drop for SecretAskComposer {
fn drop(&mut self) {
self.editor.value.zeroize();
}
}
impl fmt::Debug for SecretAskComposer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SecretAskComposer")
.field("ask", &self.ask)
.field("editor", &"[redacted]")
.field("blank_refused", &self.blank_refused)
.finish_non_exhaustive()
}
}
fn typed_reply(typed: &str) -> Option<SecretReply> {
let value = typed.trim();
(!value.is_empty()).then(|| SecretReply::Save(SecretValue::new(value)))
}
fn destination_line(name: &str, destination: &SecretDestination) -> String {
match destination {
SecretDestination::Process { command, args } => {
let line = std::iter::once(command.as_str())
.chain(args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ");
format!("{name} goes to the process `{line}`")
}
SecretDestination::Http { url } => format!("{name} goes as a header to {url}"),
_ => format!("{name} goes where the server's config sends it"),
}
}
pub(super) fn secret_ask_frame(composer: &SecretAskComposer, width: usize) -> ComposerFrame {
let ask = &composer.ask;
let mut lines = vec![styled_line(
truncate_one_line(&format!("Secret for {}", ask.server), width),
width,
Theme::input_prompt(),
LineFill::Natural,
)];
lines.extend(indented_wrapped_lines(
&destination_line(&ask.name, &ask.destination),
0,
width,
Theme::dim(),
));
if !composer.asking() {
let prompt = format!(
"the secret request closed; nothing was sent {}",
composer_chrome::join_footer_parts(["Enter/Esc dismiss"])
);
let mut frame = editor_frame(
&prompt,
composer.editor.viewport(EditorPresentation::Masked, width),
width,
);
frame.cursor.y = frame.cursor.y.saturating_add(lines.len() as u16);
lines.append(&mut frame.lines);
frame.lines = lines;
return frame;
}
if let Some(reason) = ask
.reason
.as_deref()
.filter(|reason| !reason.trim().is_empty())
{
lines.extend(indented_wrapped_lines(
reason,
0,
width,
Theme::text(),
));
}
let field = if composer.blank_refused {
format!("{} must not be empty", ask.name)
} else {
format!("enter {}", ask.name)
};
let prompt = format!(
"{field} {}",
composer_chrome::join_footer_parts(["Enter save", "Esc decline"])
);
let mut frame = editor_frame(
&prompt,
composer.editor.viewport(EditorPresentation::Masked, width),
width,
);
frame.cursor.y = frame.cursor.y.saturating_add(lines.len() as u16);
lines.append(&mut frame.lines);
frame.lines = lines;
frame
}
impl App {
pub(super) async fn open_secret_ask(
&mut self,
ask: SecretAsk,
reply: oneshot::Sender<SecretReply>,
) {
self.flush_pending_paste_burst();
let restore_side = self.side_overlay_open();
self.input_ui
.set_composer(ComposerMode::SecretAsk(SecretAskComposer::new(
ask,
reply,
restore_side,
)));
self.set_status(UserWait::Secret.message());
self.wait_for_user(UserWait::Secret).await;
}
pub(super) fn withdraw_secret_ask(&mut self) {
if let ComposerMode::SecretAsk(composer) = self.input_ui.composer_mut() {
composer.close();
}
}
pub(super) fn handle_secret_ask_key(&mut self, key: KeyEvent) -> bool {
let ComposerMode::SecretAsk(composer) = self.input_ui.composer_mut() else {
return false;
};
let outcome = composer.apply_key(key);
self.ctrl_c_streak = 0;
if outcome == SecretKey::Kept {
return true;
}
if let ComposerMode::SecretAsk(mut composer) = self.input_ui.take_composer() {
if let SecretKey::Reply(reply) = outcome {
composer.respond(reply);
}
self.restore_after_secret_ask(&composer);
}
if self.daemon_turn_runs() {
self.set_status("running");
}
true
}
fn restore_after_secret_ask(&mut self, composer: &SecretAskComposer) {
if composer.restore_side && self.side_chat.is_some() {
self.input_ui.set_composer(ComposerMode::Side);
}
}
}
#[cfg(test)]
#[path = "secret_ask_tests.rs"]
mod tests;