feat: add si cli
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context as _, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpui::{App, AsyncApp, Entity, Subscription};
|
||||
use nostr::prelude::{PublicKey, ToBech32 as _};
|
||||
use signed_state::{Backend, BackendEvent};
|
||||
|
||||
/// Command line interface for Signed.
|
||||
#[derive(Parser)]
|
||||
#[command(name = "si", version, about)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Create a new identity and store it on this device.
|
||||
Signup {
|
||||
/// Name published in the profile.
|
||||
name: String,
|
||||
/// Read the passphrase from this file instead of prompting.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
passphrase_file: Option<PathBuf>,
|
||||
},
|
||||
/// Store an existing identity on this device.
|
||||
Login {
|
||||
/// Read the credential (nsec, ncryptsec or bunker URI) from this file instead of prompting.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
credential_file: Option<PathBuf>,
|
||||
/// Read the passphrase from this file instead of prompting.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
passphrase_file: Option<PathBuf>,
|
||||
},
|
||||
/// Print the identity stored on this device.
|
||||
Whoami {
|
||||
/// Read the passphrase from this file instead of prompting.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
passphrase_file: Option<PathBuf>,
|
||||
},
|
||||
/// Remove the identity stored on this device.
|
||||
Logout,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_max_level(tracing::Level::WARN)
|
||||
.init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
gpui_platform::headless().run(move |cx| {
|
||||
// The callback runs before the platform's run loop, so the command awaits inside a foreground task.
|
||||
cx.spawn(async move |cx| {
|
||||
let mut code = 0;
|
||||
|
||||
if let Err(error) = run(cli.command, cx).await {
|
||||
eprintln!("error: {error:#}");
|
||||
code = 1;
|
||||
}
|
||||
|
||||
if let Err(error) = std::io::stdout().flush() {
|
||||
eprintln!("error: failed to write output: {error}");
|
||||
code = 1;
|
||||
}
|
||||
|
||||
// Quitting the platform loop does not carry an exit code, so the process ends here.
|
||||
std::process::exit(code);
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
}
|
||||
|
||||
async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
||||
match command {
|
||||
Command::Signup {
|
||||
name,
|
||||
passphrase_file,
|
||||
} => signup(&name, passphrase_file.as_deref(), cx).await,
|
||||
Command::Login {
|
||||
credential_file,
|
||||
passphrase_file,
|
||||
} => login(credential_file.as_deref(), passphrase_file.as_deref(), cx).await,
|
||||
Command::Whoami { passphrase_file } => whoami(passphrase_file.as_deref(), cx).await,
|
||||
Command::Logout => logout(cx).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the stores shared with the desktop app and starts forwarding the backend events.
|
||||
fn open(
|
||||
cx: &mut AsyncApp,
|
||||
) -> anyhow::Result<(Entity<Backend>, flume::Receiver<BackendEvent>, Subscription)> {
|
||||
cx.update(signed_state::init)?;
|
||||
let backend = cx.update(|cx| Backend::global(cx));
|
||||
|
||||
let (sender, receiver) = flume::unbounded();
|
||||
// The returned subscription keeps the forwarding alive; dropping it ends it.
|
||||
let subscription = cx.subscribe(&backend, move |_, event: &BackendEvent, _| {
|
||||
// Sending fails only once the command stopped listening.
|
||||
sender.send(event.clone()).ok();
|
||||
});
|
||||
|
||||
Ok((backend, receiver, subscription))
|
||||
}
|
||||
|
||||
/// Waits for the next backend event.
|
||||
async fn next_event(receiver: &flume::Receiver<BackendEvent>) -> anyhow::Result<BackendEvent> {
|
||||
Ok(receiver.recv_async().await?)
|
||||
}
|
||||
|
||||
/// The public key of the restored signer.
|
||||
fn current_user(backend: &Entity<Backend>, cx: &App) -> anyhow::Result<PublicKey> {
|
||||
backend
|
||||
.read(cx)
|
||||
.current_user()
|
||||
.context("the signer changed without an identity")
|
||||
}
|
||||
|
||||
/// How the device is signed in once its stored credential was read.
|
||||
enum Identity {
|
||||
SignedIn(PublicKey),
|
||||
PassphraseRequired,
|
||||
SignedOut,
|
||||
}
|
||||
|
||||
/// Waits for the stored credential to be read.
|
||||
async fn restore(
|
||||
backend: &Entity<Backend>,
|
||||
receiver: &flume::Receiver<BackendEvent>,
|
||||
cx: &AsyncApp,
|
||||
) -> anyhow::Result<Identity> {
|
||||
let mut failure = None;
|
||||
|
||||
loop {
|
||||
match next_event(receiver).await? {
|
||||
BackendEvent::SignerChanged => {
|
||||
return Ok(Identity::SignedIn(
|
||||
cx.update(|cx| current_user(backend, cx))?,
|
||||
));
|
||||
}
|
||||
BackendEvent::PassphraseRequired => return Ok(Identity::PassphraseRequired),
|
||||
BackendEvent::SignerRequired => {
|
||||
// A failed read is reported first, then the signed-out state.
|
||||
if let Some(message) = failure {
|
||||
bail!("{message}");
|
||||
}
|
||||
|
||||
return Ok(Identity::SignedOut);
|
||||
}
|
||||
BackendEvent::Error(message) => failure = Some(message),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails when the device already holds a credential, since a second one would shadow it on restore.
|
||||
async fn require_signed_out(
|
||||
backend: &Entity<Backend>,
|
||||
receiver: &flume::Receiver<BackendEvent>,
|
||||
cx: &AsyncApp,
|
||||
) -> anyhow::Result<()> {
|
||||
match restore(backend, receiver, cx).await? {
|
||||
Identity::SignedOut => Ok(()),
|
||||
Identity::SignedIn(public_key) => {
|
||||
bail!("this device already holds an identity ({public_key}); run `si logout` first")
|
||||
}
|
||||
Identity::PassphraseRequired => {
|
||||
bail!("this device already holds an encrypted identity; run `si logout` first")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn whoami(passphrase_file: Option<&Path>, cx: &mut AsyncApp) -> anyhow::Result<()> {
|
||||
let (backend, receiver, _subscription) = open(cx)?;
|
||||
|
||||
let public_key = match restore(&backend, &receiver, cx).await? {
|
||||
Identity::SignedIn(public_key) => public_key,
|
||||
Identity::PassphraseRequired => {
|
||||
let passphrase = read_passphrase(passphrase_file)?;
|
||||
backend
|
||||
.update(cx, |backend, cx| {
|
||||
backend.restore_with_passphrase(&passphrase, cx)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
Identity::SignedOut => {
|
||||
bail!("no identity on this device; run `si signup` or `si login` first")
|
||||
}
|
||||
};
|
||||
|
||||
print_identity(public_key)
|
||||
}
|
||||
|
||||
async fn signup(
|
||||
name: &str,
|
||||
passphrase_file: Option<&Path>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> anyhow::Result<()> {
|
||||
let (backend, receiver, _subscription) = open(cx)?;
|
||||
|
||||
require_signed_out(&backend, &receiver, cx).await?;
|
||||
|
||||
let passphrase = new_passphrase(passphrase_file)?;
|
||||
let public_key = backend
|
||||
.update(cx, |backend, cx| {
|
||||
backend.create_identity(name, &passphrase, cx)
|
||||
})
|
||||
.await?;
|
||||
print_identity(public_key)?;
|
||||
|
||||
// The identity is stored already; wait so exiting does not drop the events still being sent.
|
||||
loop {
|
||||
match next_event(&receiver).await? {
|
||||
BackendEvent::IdentityPublished(Ok(())) => return Ok(()),
|
||||
BackendEvent::IdentityPublished(Err(message)) => bail!("{message}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn login(
|
||||
credential_file: Option<&Path>,
|
||||
passphrase_file: Option<&Path>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> anyhow::Result<()> {
|
||||
let (backend, receiver, _subscription) = open(cx)?;
|
||||
|
||||
require_signed_out(&backend, &receiver, cx).await?;
|
||||
|
||||
let credential = read_credential(credential_file)?;
|
||||
let credential = credential.trim();
|
||||
|
||||
let public_key = if credential.starts_with("nsec1") {
|
||||
let passphrase = new_passphrase(passphrase_file)?;
|
||||
backend
|
||||
.update(cx, |backend, cx| {
|
||||
backend.import_nsec(credential, &passphrase, cx)
|
||||
})
|
||||
.await?
|
||||
} else if credential.starts_with("ncryptsec1") {
|
||||
let passphrase = read_passphrase(passphrase_file)?;
|
||||
backend
|
||||
.update(cx, |backend, cx| {
|
||||
backend.import_ncryptsec(credential, &passphrase, cx)
|
||||
})
|
||||
.await?
|
||||
} else if credential.starts_with("bunker://") {
|
||||
backend
|
||||
.update(cx, |backend, cx| backend.import_bunker(credential, cx))
|
||||
.await?
|
||||
} else {
|
||||
bail!("the credential must be an nsec, ncryptsec or bunker:// URI");
|
||||
};
|
||||
|
||||
print_identity(public_key)
|
||||
}
|
||||
|
||||
async fn logout(cx: &mut AsyncApp) -> anyhow::Result<()> {
|
||||
let (backend, receiver, _subscription) = open(cx)?;
|
||||
|
||||
if let Identity::SignedOut = restore(&backend, &receiver, cx).await? {
|
||||
bail!("no identity on this device");
|
||||
}
|
||||
|
||||
backend.update(cx, |backend, cx| backend.sign_out(cx)).await
|
||||
}
|
||||
|
||||
/// Reads one line from a file, without its line ending.
|
||||
fn read_line(path: &Path) -> anyhow::Result<String> {
|
||||
let line = std::fs::read_to_string(path)?;
|
||||
Ok(line.trim_end_matches(['\r', '\n']).to_owned())
|
||||
}
|
||||
|
||||
/// Reads the passphrase from `path`, or from the terminal without echoing it.
|
||||
fn read_passphrase(path: Option<&Path>) -> anyhow::Result<String> {
|
||||
match path {
|
||||
Some(path) => read_line(path),
|
||||
None => Ok(rpassword::prompt_password("Passphrase: ")?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the passphrase for a new key, confirming it when it is typed.
|
||||
fn new_passphrase(path: Option<&Path>) -> anyhow::Result<String> {
|
||||
let Some(path) = path else {
|
||||
let passphrase = rpassword::prompt_password("Choose a passphrase: ")?;
|
||||
if passphrase != rpassword::prompt_password("Confirm passphrase: ")? {
|
||||
bail!("passphrases do not match");
|
||||
}
|
||||
|
||||
return Ok(passphrase);
|
||||
};
|
||||
|
||||
read_line(path)
|
||||
}
|
||||
|
||||
/// Reads the credential from `path`, or from the terminal without echoing it.
|
||||
fn read_credential(path: Option<&Path>) -> anyhow::Result<String> {
|
||||
match path {
|
||||
Some(path) => read_line(path),
|
||||
None => Ok(rpassword::prompt_password(
|
||||
"Credential (nsec, ncryptsec or bunker URI): ",
|
||||
)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_identity(public_key: PublicKey) -> anyhow::Result<()> {
|
||||
println!("npub: {}", public_key.to_bech32()?);
|
||||
println!("hex: {public_key}");
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user