first commit

This commit is contained in:
yves committed 2026-11-20 21:47:33 +01:00
commit 6d3ea3e2a6
43 files changed
+8204

No files matched your search

+469
View File
@@ -0,0 +1,469 @@
//! `meow`: command line client for the Meow v2 protocol.
//!
//! Without a sub-command, `meow` synchronises (checks every server once).
//! Results go to stdout; diagnostics go to stderr.
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand};
use meow_client::{Content, Event, MeowClient, DEFAULT_INVITATION_TTL};
use meow_crypto::password::KdfParams;
#[derive(Parser)]
#[command(name = "meow", version, about = "Meow v2 secure messaging CLI")]
struct Cli {
/// Identity file.
#[arg(short, long, env = "MEOW_IDENTITY", global = true)]
identity: Option<PathBuf>,
/// Password protecting the identity file.
#[arg(short, long, env = "MEOW_PASSWORD", hide_env_values = true, global = true)]
password: Option<String>,
/// Use very weak key derivation (tests only!).
#[arg(long, env = "MEOW_INSECURE_FAST_KDF", hide = true, global = true)]
insecure_fast_kdf: bool,
/// Where received files are written.
#[arg(long, env = "MEOW_DOWNLOADS", default_value = "downloads", global = true)]
downloads: PathBuf,
/// More logs on stderr (repeat for more).
#[arg(short, long, action = clap::ArgAction::Count, global = true)]
verbose: u8,
#[command(subcommand)]
command: Option<Cmd>,
}
#[derive(Subcommand)]
enum Cmd {
/// Manage the identity.
#[command(subcommand)]
Identity(IdentityCmd),
/// Manage message servers.
#[command(subcommand)]
Server(ServerCmd),
/// Manage contacts.
#[command(subcommand)]
Contact(ContactCmd),
/// Invitation through files (4 steps).
#[command(subcommand)]
Invitation(InvitationCmd),
/// Invitation through a server shortcode.
#[command(subcommand, name = "server-invitation")]
ServerInvitation(ServerInvitationCmd),
/// Send a text message.
Send {
contact: String,
#[arg(required = true, num_args = 1..)]
text: Vec<String>,
},
/// Send a file.
#[command(name = "send-file")]
SendFile { contact: String, file: PathBuf },
/// Check every server once (default command).
Sync {
/// Long-poll for up to this many seconds.
#[arg(short, long, default_value_t = 0)]
wait: u64,
},
/// Wait for messages continuously.
Longpoll {
#[arg(short, long, default_value_t = 30)]
wait: u64,
/// Exit after the first batch of events (or the first timeout).
#[arg(short, long)]
exit: bool,
},
/// Show the conversation with a contact.
History { contact: String },
}
#[derive(Subcommand)]
enum IdentityCmd {
/// Create a new identity file.
Create {
nickname: String,
#[arg(long)]
force: bool,
},
/// Show the identity summary.
Show,
}
#[derive(Subcommand)]
enum ServerCmd {
/// Add a server by URL (its card is fetched and pinned).
Add {
url: String,
},
List,
Remove {
server: String,
},
}
#[derive(Subcommand)]
enum ContactCmd {
List,
Show { name: String },
Remove { name: String },
}
#[derive(Args)]
struct ServerSel {
/// Comma-separated server URLs or names (default: all my servers).
#[arg(short, long, value_delimiter = ',')]
servers: Vec<String>,
}
#[derive(Subcommand)]
enum InvitationCmd {
/// Step 1: create an invitation file for <contact>.
Create {
contact: String,
#[command(flatten)]
sel: ServerSel,
#[arg(short, long, default_value = "")]
message: String,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// Show what an invitation file contains.
Check { file: PathBuf },
/// Step 2: answer an invitation file.
Answer {
file: PathBuf,
#[command(flatten)]
sel: ServerSel,
/// Local name for the contact (default: the name they gave).
#[arg(short, long)]
name: Option<String>,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// Step 3: accept an answer file, produce the confirmation file.
Accept {
file: PathBuf,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// Step 4: finalize with the confirmation file (sends the ack over the network).
Finalize { file: PathBuf },
}
#[derive(Subcommand)]
enum ServerInvitationCmd {
/// Publish an invitation on a server; prints its URL on stdout.
Create {
contact: String,
#[command(flatten)]
sel: ServerSel,
#[arg(short, long, default_value = "")]
message: String,
/// Password the invitee must give (transmit it out of band).
#[arg(long, default_value = "")]
invitation_password: String,
},
/// Fetch and answer a published invitation.
Get {
url: String,
#[command(flatten)]
sel: ServerSel,
#[arg(short, long)]
name: Option<String>,
#[arg(long, default_value = "")]
invitation_password: String,
},
}
fn default_identity() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default()
.join(".meow2")
.join("default.mwid2")
}
struct Ctx {
identity: PathBuf,
password: String,
kdf: KdfParams,
downloads: PathBuf,
}
impl Ctx {
async fn open(&self) -> Result<MeowClient> {
MeowClient::open(&self.identity, &self.password, self.kdf)
.await
.with_context(|| format!("cannot open identity {}", self.identity.display()))
}
}
#[tokio::main]
async fn main() {
if let Err(e) = run().await {
eprintln!("error: {e:#}");
std::process::exit(1);
}
}
async fn run() -> Result<()> {
let cli = Cli::parse();
let level = match cli.verbose {
0 => "warn",
1 => "info",
_ => "debug",
};
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| level.into()))
.with_writer(std::io::stderr)
.init();
let Some(password) = cli.password else {
bail!("a password is required: use --password or the MEOW_PASSWORD environment variable");
};
let ctx = Ctx {
identity: cli.identity.unwrap_or_else(default_identity),
password,
kdf: if cli.insecure_fast_kdf {
KdfParams::INSECURE_TEST
} else {
KdfParams::DEFAULT
},
downloads: cli.downloads,
};
match cli.command.unwrap_or(Cmd::Sync { wait: 0 }) {
Cmd::Identity(IdentityCmd::Create { nickname, force }) => {
if let Some(dir) = ctx.identity.parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir)?;
}
MeowClient::create(&ctx.identity, &nickname, &ctx.password, ctx.kdf, force).await?;
println!("identity {nickname} created in {}", ctx.identity.display());
}
Cmd::Identity(IdentityCmd::Show) => {
let c = ctx.open().await?;
println!("nickname: {}", c.nickname());
println!("servers: {}", c.servers().len());
println!("contacts: {}", c.contacts().len());
}
Cmd::Server(ServerCmd::Add { url }) => {
let mut c = ctx.open().await?;
let s = c.add_server(&url).await?;
println!("added {} ({}) key {}", s.url, s.name, s.sign_key.fingerprint());
}
Cmd::Server(ServerCmd::List) => {
let c = ctx.open().await?;
for s in c.servers() {
println!("{}\t{}\t{}", s.url, s.name, s.sign_key.fingerprint());
}
}
Cmd::Server(ServerCmd::Remove { server }) => {
ctx.open().await?.remove_server(&server).await?;
println!("removed {server}");
}
Cmd::Contact(ContactCmd::List) => {
let c = ctx.open().await?;
for k in c.contacts() {
println!("{}\t{:?}", k.name, k.state);
}
}
Cmd::Contact(ContactCmd::Show { name }) => {
let c = ctx.open().await?;
let k = c.contact(&name)?;
println!("name: {}", k.name);
println!("presented as: {}", k.my_name);
println!("state: {:?}", k.state);
println!("id: {}", k.id);
if let Some(p) = &k.peer {
println!("their name: {}", p.name);
println!(
"their servers: {}",
p.pull_servers
.iter()
.map(|s| s.url.as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
println!(
"my servers: {}",
k.my_pull_servers
.iter()
.map(|s| s.url.as_str())
.collect::<Vec<_>>()
.join(", ")
);
if let Some(sn) = k.safety_number() {
println!("safety number: {sn}");
}
}
Cmd::Contact(ContactCmd::Remove { name }) => {
ctx.open().await?.remove_contact(&name).await?;
println!("removed {name}");
}
Cmd::Invitation(cmd) => invitation(&ctx, cmd).await?,
Cmd::ServerInvitation(ServerInvitationCmd::Create {
contact,
sel,
message,
invitation_password,
}) => {
let mut c = ctx.open().await?;
let url = c
.publish_invitation(
&contact,
&sel.servers,
&message,
&invitation_password,
DEFAULT_INVITATION_TTL,
)
.await?;
println!("{url}");
}
Cmd::ServerInvitation(ServerInvitationCmd::Get {
url,
sel,
name,
invitation_password,
}) => {
let mut c = ctx.open().await?;
let who = c
.accept_published_invitation(&url, &invitation_password, name.as_deref(), &sel.servers)
.await?;
println!("answered invitation from {who}");
}
Cmd::Send { contact, text } => {
let r = ctx.open().await?.send_text(&contact, &text.join(" ")).await?;
println!("sent to {contact} ({} server(s))", r.delivered_to);
}
Cmd::SendFile { contact, file } => {
let r = ctx.open().await?.send_file(&contact, &file).await?;
println!("sent {} to {contact} ({} server(s))", file.display(), r.delivered_to);
}
Cmd::Sync { wait } => {
let mut c = ctx.open().await?;
let ev = c.sync(Duration::from_secs(wait)).await?;
print_events(&ctx, &ev)?;
}
Cmd::Longpoll { wait, exit } => {
let mut c = ctx.open().await?;
loop {
let ev = c.sync(Duration::from_secs(wait)).await?;
print_events(&ctx, &ev)?;
if exit {
break;
}
}
}
Cmd::History { contact } => {
let c = ctx.open().await?;
for h in c.history(&contact)? {
let who = if h.outbound {
c.nickname().to_string()
} else {
contact.clone()
};
match &h.content {
Content::Text(t) => println!("[{who}] {t}"),
Content::File { name, size } => println!("[{who}] <file {name}, {size} bytes>"),
}
}
}
}
Ok(())
}
fn stem(p: &Path) -> String {
p.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default()
}
async fn invitation(ctx: &Ctx, cmd: InvitationCmd) -> Result<()> {
match cmd {
InvitationCmd::Create {
contact,
sel,
message,
out,
} => {
let mut c = ctx.open().await?;
let offer = c
.create_invitation(&contact, &sel.servers, &message, DEFAULT_INVITATION_TTL)
.await?;
let out = out.unwrap_or_else(|| PathBuf::from(format!("{}-{contact}.mwiv2", c.nickname())));
std::fs::write(&out, offer)?;
println!("{}", out.display());
}
InvitationCmd::Check { file } => {
let c = ctx.open().await?;
let info = c.inspect_invitation(&std::fs::read(&file)?)?;
println!("from: {}", info.initiator_name);
println!("message: {}", info.message);
println!("expires at: {}", info.expires_at);
println!(
"servers: {}",
info.answer_servers
.iter()
.map(|s| s.url.as_str())
.collect::<Vec<_>>()
.join(", ")
);
}
InvitationCmd::Answer { file, sel, name, out } => {
let mut c = ctx.open().await?;
let offer = std::fs::read(&file)?;
let initiator = c.inspect_invitation(&offer)?.initiator_name;
let answer = c.answer_invitation(&offer, name.as_deref(), &sel.servers).await?;
let out = out.unwrap_or_else(|| PathBuf::from(format!("{}-{initiator}.mwiv2", c.nickname())));
std::fs::write(&out, answer)?;
println!("{}", out.display());
}
InvitationCmd::Accept { file, out } => {
let mut c = ctx.open().await?;
let confirm = c.accept_answer(&std::fs::read(&file)?).await?;
let out = out.unwrap_or_else(|| {
// bob accepting "alice-bob.mwiv2" writes "bob-alice-step3.mwiv2"
let s = stem(&file);
let other = s.split('-').next().unwrap_or("contact").to_string();
PathBuf::from(format!("{}-{other}-step3.mwiv2", c.nickname()))
});
std::fs::write(&out, confirm)?;
println!("{}", out.display());
}
InvitationCmd::Finalize { file } => {
let mut c = ctx.open().await?;
let name = c.finalize_invitation(&std::fs::read(&file)?).await?;
println!("contact {name} is active");
}
}
Ok(())
}
fn safe_name(name: &str) -> String {
let base = Path::new(name)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if base.is_empty() || base.starts_with('.') {
"received.bin".into()
} else {
base
}
}
fn print_events(ctx: &Ctx, events: &[Event]) -> Result<()> {
for e in events {
match e {
Event::Message { contact, text, .. } => println!("[{contact}] {text}"),
Event::File { contact, name, data } => {
std::fs::create_dir_all(&ctx.downloads)?;
let path = ctx.downloads.join(safe_name(name));
std::fs::write(&path, data)?;
println!("[{contact}] file saved to {}", path.display());
}
Event::InvitationAccepted { contact } => println!("invitation accepted by {contact}, confirmation sent"),
Event::ContactActivated { contact } => println!("contact {contact} is active"),
}
}
Ok(())
}