use crate::ui::Style;
use anyhow::{bail, Context, Result};
use eclipse_core::auth;
use std::io::Write;
pub struct Request {
pub user: Option<String>,
pub stdin: bool,
}
pub fn passwd(
req: &Request,
env: eclipse_core::config::EnvFn<'_>,
style: &Style,
) -> Result<Vec<String>> {
let dir = eclipse_core::config::config_dir(env)
.context("no config directory: set ECLIPSE_HOME so there is a `.env` to write")?;
let path = dir.join(".env");
let existing = std::fs::read_to_string(&path).unwrap_or_default();
let current_user = parse_var(&existing, auth::USER_VAR);
let user = match (&req.user, current_user) {
(Some(user), _) => user.clone(),
(None, Some(user)) => user,
(None, None) => {
if req.stdin || !is_tty() {
bail!(
"no username: pass `--user <name>`, or set {} in .env. This invocation reads \
its password from stdin, so it cannot also ask for a name",
auth::USER_VAR
);
}
let typed = prompt("User: ")?;
if typed.trim().is_empty() {
bail!("a username is required: it is half of the sign-in");
}
typed.trim().to_string()
}
};
if let Some(bad) = user
.chars()
.find(|c| c.is_whitespace() || *c == '#' || *c == '"' || *c == '\'')
{
let named = if bad.is_whitespace() {
"a space".to_string()
} else {
format!("`{bad}`")
};
bail!(
"the username is not usable: it contains {named}. No spaces, quotes or `#` in a \
username — they would need quoting in .env, and getting that wrong turns a working \
login into a file that says something else"
);
}
let password = if req.stdin || !is_tty() {
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.context("reading the password from stdin")?;
line.trim_end_matches(['\n', '\r']).to_string()
} else {
let first = prompt_quiet("Password: ")?;
let again = prompt_quiet("Password again: ")?;
if first != again {
bail!("the two passwords differ; nothing was written");
}
first
};
if password.chars().count() < 8 {
bail!(
"the password must be at least 8 characters ({} given)",
password.chars().count()
);
}
let hash = auth::hash_password(&password)?;
auth::write_env_vars(&path, &[(auth::USER_VAR, &user), (auth::HASH_VAR, &hash)])?;
let mut out = vec![
format!(
"{} {} ({}, {} rounds)",
style.bold("wrote"),
path.display(),
user,
auth::ITERATIONS
),
format!(" {}", auth::USER_VAR),
format!(" {}", auth::HASH_VAR),
];
out.push(String::new());
out.push(
"The password is not printed, not stored, and not in your shell history. Restart the \
dashboard for it to take effect; until then `web.auth_token` is still the door."
.to_string(),
);
Ok(out)
}
fn prompt(what: &str) -> Result<String> {
print!("{what}");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.context("reading your answer")?;
Ok(line.trim_end_matches(['\n', '\r']).to_string())
}
fn is_tty() -> bool {
#[cfg(unix)]
{
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
#[cfg(not(unix))]
{
true
}
}
fn prompt_quiet(what: &str) -> Result<String> {
print!("{what}");
std::io::stdout().flush().ok();
#[cfg(unix)]
let _guard = EchoOff::new();
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.context("reading the password")?;
println!();
Ok(line.trim_end_matches(['\n', '\r']).to_string())
}
#[cfg(unix)]
struct EchoOff {
saved: Option<libc::termios>,
}
#[cfg(unix)]
impl EchoOff {
fn new() -> Self {
unsafe {
let mut term: libc::termios = std::mem::zeroed();
if libc::tcgetattr(libc::STDIN_FILENO, &mut term) != 0 {
return Self { saved: None };
}
let saved = term;
term.c_lflag &= !libc::ECHO;
libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &term);
Self { saved: Some(saved) }
}
}
}
#[cfg(unix)]
impl Drop for EchoOff {
fn drop(&mut self) {
if let Some(saved) = self.saved {
unsafe {
libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &saved);
}
}
}
}
fn parse_var(text: &str, key: &str) -> Option<String> {
for line in text.lines() {
let line = line.trim();
let body = line.strip_prefix("export ").unwrap_or(line).trim_start();
let Some(rest) = body.strip_prefix(key) else {
continue;
};
let Some(value) = rest.strip_prefix('=') else {
continue;
};
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value);
if !value.is_empty() {
return Some(value.to_string());
}
}
None
}