Skip to content
1        10        20        30        40        50        60        70        80        90        1001use anyhow::{Context, Result, bail};23use crate::auth::Scope;4use crate::client;5use crate::config::Config;6use crate::db;7use crate::tokens;8use crate::users;910/// Parsed command-line arguments: positionals, `--name value` options (repeatable), and11/// bare `--flag`s. Only the names listed by the caller are accepted.12#[derive(Debug, Default)]13pub struct Args {14    pub positional: Vec<String>,15    options: Vec<(String, String)>,16    flags: Vec<String>,17}1819impl Args {20    pub fn parse(raw: &[String], takes_value: &[&str], flags: &[&str]) -> Result<Self> {21        let mut parsed = Self::default();22        let mut iter = raw.iter();23        while let Some(arg) = iter.next() {24            let Some(name) = arg.strip_prefix("--") else {25                parsed.positional.push(arg.clone());26                continue;27            };28            if flags.contains(&name) {29                parsed.flags.push(name.to_string());30            } else if takes_value.contains(&name) {31                let value = iter32                    .next()33                    .with_context(|| format!("--{name} needs a value"))?;34                parsed.options.push((name.to_string(), value.clone()));35            } else {36                bail!("unknown option --{name}");37            }38        }39        Ok(parsed)40    }4142    pub fn value(&self, name: &str) -> Option<&str> {43        self.options44            .iter()45            .rev()46            .find(|(option, _)| option == name)47            .map(|(_, value)| value.as_str())48    }4950    pub fn values(&self, name: &str) -> Vec<String> {51        self.options52            .iter()53            .filter(|(option, _)| option == name)54            .map(|(_, value)| value.clone())55            .collect()56    }5758    pub fn has(&self, flag: &str) -> bool {59        self.flags.iter().any(|set| set == flag)60    }61}6263const HELP: &str = "\64cairn — an archive for anything worth remembering6566Server:67  cairn serve                         Run the HTTP server (BIND_ADDRESS, PORT, DB_PATH)68  cairn token create <name> [--read-only]69                                      Print a new access token (shown once)70  cairn token list                    List tokens (secrets are never shown)71  cairn token revoke <id>             Revoke a token72  cairn user create <username>        Create a sign-in; prints a generated password (shown once)73  cairn user reset <username>         Replace a user's password with a generated one7475Client (needs CAIRN_TOKEN; CAIRN_URL defaults to https://cairn.silenlocatelli.ch):76  cairn add [--title T] [--tag X]... [--meta k=v]... [--file F]... [TEXT | -]77                                      Save text and/or files; prints the new id78  cairn ls [--tag X] [--meta k=v]... [--sort created|updated|title]79           [--order asc|desc] [--limit N] [--offset N]80                                      List items81  cairn search [--tag X] [--meta k=v]... [--sort …] WORDS...82                                      Full-text search (words also match filenames)83  cairn get <id>                      Show an item, its metadata and files84  cairn edit <id> [--title T] [--content-file FILE | -] [--meta k=v]...85                                      Change title, content, or metadata86  cairn tag <id> <tag>...             Add tags87  cairn untag <id> <tag>              Remove a tag88  cairn attach <id> FILE...           Add files to an item89  cairn fetch <file-id> [--out FILE]  Download a file (to stdout without --out)90  cairn detach <file-id>              Remove a file91  cairn rm <id>                       Delete an item and its files92  cairn tags                          List tags with counts93  cairn whoami                        Show the token in use94";9596pub async fn run(args: Vec<String>) -> Result<()> {97    let Some((command, rest)) = args.split_first() else {98        print!("{HELP}");99        return Ok(());100    };101    match command.as_str() {102        "serve" => crate::server::run(Config::from_env()?).await,103        "token" => token(rest),104        "user" => user(rest),105        "help" | "-h" | "--help" => {106            print!("{HELP}");107            Ok(())108        }109        _ => client::run(command, rest).await,110    }111}112113/// Accounts for the web sign-in. Passwords are generated here, so the one printed is the114/// only copy outside the hash; the person changes it on the Account page.115fn user(raw: &[String]) -> Result<()> {116    let config = Config::from_env()?;117    let connection = db::open(&config.db_path)?;118    let Some((action, rest)) = raw.split_first() else {119        bail!("usage: cairn user create <username> | reset <username>");120    };121    let username = rest122        .first()123        .context("usage: cairn user create|reset <username>")?;124    let password = users::generate_password();125    match action.as_str() {126        "create" => {127            users::create(&connection, username, &password)?;128            println!("{password}");129            eprintln!(130                "Created user {username}. Sign in with this password; it cannot be shown again."131            );132        }133        "reset" => {134            if !users::reset_password(&connection, username, &password)? {135                bail!("no user named {username:?}");136            }137            println!("{password}");138            eprintln!("Reset the password for {username}. The old one no longer works.");139        }140        other => bail!("unknown user command {other:?}"),141    }142    Ok(())143}144145fn token(raw: &[String]) -> Result<()> {146    let config = Config::from_env()?;147    let connection = db::open(&config.db_path)?;148    let Some((action, rest)) = raw.split_first() else {149        bail!("usage: cairn token create <name> [--read-only] | list | revoke <id>");150    };151    match action.as_str() {152        "create" => {153            let args = Args::parse(rest, &[], &["read-only"])?;154            let name = args155                .positional156                .first()157                .context("usage: cairn token create <name> [--read-only]")?;158            let scopes = if args.has("read-only") {159                vec![Scope::Read]160            } else {161                vec![Scope::Read, Scope::Write]162            };163            let issued = tokens::create(&connection, name, &scopes)?;164            // The secret goes to stdout alone so `export CAIRN_TOKEN=$(cairn token create x)` works.165            println!("{}", issued.secret);166            eprintln!(167                "Created token {} ({}, scopes: {}). Store it now; it cannot be shown again.",168                issued.info.id,169                issued.info.name,170                Scope::join(&issued.info.scopes)171            );172        }173        "list" => {174            for token in tokens::list(&connection)? {175                println!(176                    "{}  {:<20}  ...{}  {:<11}  {}",177                    token.id,178                    token.name,179                    token.hint,180                    Scope::join(&token.scopes),181                    token.created_at182                );183            }184        }185        "revoke" => {186            let id = rest.first().context("usage: cairn token revoke <id>")?;187            if tokens::delete(&connection, id)? {188                println!("Revoked {id}");189            } else {190                bail!("no token with id {id}");191            }192        }193        other => bail!("unknown token command {other:?}"),194    }195    Ok(())196}